Search code examples
javawrapperprimitive-typesunboxing

Unexpected behaviour with Java unboxing


Map<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
int value = map.get(2);
System.out.println(v);

On executing the above code I find below exception Exception in thread "main" java.lang.NullPointerException

but if place an Integer in the place int primitive type in the 3rd line, all working well. So, the question in here is why doesn't java unboxing take care of this null value internally and assign null to variable called value?


Solution

  • So, the question in here is why doesn't java unboxing take care of this null value internally and assign null to variable called value?

    Your value variable is an int primitive. A primitive cannot have a null value. Only objects can.