Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check in map gets null pointer exception

I am trying to use a Java HashMap. Using map.get("A") to get a value for a key from the map resulted in a NullPointerException. Then I used if(map.get("A")) to avoid a NullPointerException being thrown, but it gets thrown anyway.

What am I doing wrong?

like image 765
Sara Avatar asked Oct 20 '25 01:10

Sara


1 Answers

I have answering my own question. I have used to check

         if(map.containsKey("A"))
                 String b =  map.get("A")

rather than

    if(map.get("A") != null)
            map.get("A")

It will help me to avoid null pointer exception

like image 179
Sara Avatar answered Oct 21 '25 18:10

Sara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!