Java HashMap get method null pointer exception

Change

if ( myMap.get(c) )

to

if ( myMap.containsKey(c) && myMap.get(c))

If c is not contained in myMap, it will return null, which can't be unboxed as a boolean.

Try :

Boolean b = myMap.get(c);
if(b != null && b){
...

If there is no entity with required Character in map, then map.get(key) returns null and inside if statement it leads to NullPointerException throwing.


If myMap doesn't contain a key that matches c, then myMap.get(c) will return null. In that case, when the JVM unboxes what it expects to be a java.lang.Boolean object into a boolean primitive to execute the condition, it founds a null object and therefore throws a java.lang.NullPointerException.

The following block is equivalent to what you have in your example and should make it easier to understand why you would have a NullPointerException:

if (((Boolean) myMap.get(c)).booleanValue()) 

I would re-write your original condition as:

if ( myMap.containsKey(c) )

I hope this helps.