Unexpected behaviour with Java unboxing

59 Views Asked by At
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?

2

There are 2 best solutions below

1
Robby Cornelissen On BEST ANSWER

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.

0
HolyLance On

int is a primitive type.

null is not a primitive type, it represents a nonexistent object reference and cannot be autoboxed to a primitive type.

int value = null; which could be seen as more "explicit" version of the question you asking for, does not even compile.