Null Integer object assigned to primitive int throws NullPointerException

6.5k views Asked by At
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?

3

There are 3 answers

2
xlecoustillier On

Integer is an object. Therefore it is nullable.

Integer i = null;

is correct.

int, on the other hand, is a primitive value, therefore not nullable.

int j = i;

is equivalent to

int j = null;

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.

Integer i = 12;
int j = i;
System.out.println(j);

outputs 12 as expected.

1
Chris Mantle On

This fails because when you assign i to j, the JVM attempts to unbox the primitive int value contained in i to assign it to j. As i is null, this fails with a null pointer exception.

0
Sahin Sarkar On

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.