1

From java docs of Map

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

But following code is throwing Null Pointer exception.

public class Main {
    public static void main(String args[]) throws Exception {
        boolean bool = false;
        Map<String, Boolean> map = new HashMap<>();
        boolean r = bool ? false : map.get("a");
    }
}

Can some one help me understand this behavior.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • What did you not understand? Read again, *..or **null** if this map contains no mapping for the key.* – Naman Jan 06 '20 at 06:55
  • https://stackoverflow.com/questions/34895627/java-parse-boolean-that-may-be-null-to-boolean , his could be helpful. – Vishwa Ratna Jan 06 '20 at 07:05

3 Answers3

9

The issue here is not with the hashmap, but rather the auto-unboxing of the result to a primitive boolean.

Use:

    Map<String, Boolean> map = new HashMap<>();
    Boolean r = map.get("a");

Notice that r is a "big b" Boolean wrapper object, not a primitive boolean.

As MadaManu points out, be aware that r can be null, which can be quite surprising to readers of your code. You might instead like to use:

    Map<String, Boolean> map = new HashMap<>();
    boolean r = map.getOrDefault("a", false);

... if you wish to treat the missing key as the same as false.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
4

The get is returning null, as the map is empty. The NullPointerException occurs on the attempt to convert ("unbox") null into a primitive boolean to give the ternary expression a primitive boolean type, aligned with the false.

The assignment is never even attempted, so that's not relevant.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
1

From JLS 5.1.8. Unboxing Conversion

If r is null, unboxing conversion throws a NullPointerException

In your case map.get("a") returns null and then Unboxing throws this exception .

You can use Boolean for workaround:

Boolean r = map.get("a");
// here r will be null.
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89