Integer i = null;
int j = i;
System.out.println(j);
Why does it throw NullPointerException
and doesn't print the value of j
as 0
?
Integer i = null;
int j = i;
System.out.println(j);
Why does it throw NullPointerException
and doesn't print the value of j
as 0
?
This so happens, because when an int type variable is assigned an Integer type object, the java compiler tries to unbox the object's value by calling the intValue() method on the Integer reference. In your case, the java compiler tries to unbox the object i by calling i.intValue()
.
Now since i is null, calling any methods on the null reference results in NullPointerException which is what happened in your case.
Integer
is an object. Therefore it is nullable.is correct.
int
, on the other hand, is a primitive value, therefore not nullable.is equivalent to
which is incorrect, and throws a
NullPointerException
.Expanding thanks to JNYRanger:
This implicit conversion from a primitive value object wrapper to its primitive equivalent is called "unboxing" and works as soon as the object holds a not null value.
outputs 12 as expected.