-1
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?

Ellis
  • 173
  • 13
Vivek Paliwal
  • 27
  • 1
  • 2

3 Answers3

5

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.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
  • 1
    This is the correct answer, but I just wanted to add on to this on: If OP had actually assigned a value to j at any point then the statement would be valid. This is due to a process known as 'unboxing,' which is the conversion of an object to a primitive. When the unboxing fails in this situation, the NullPointerException is thrown. (@XLAnt I know you probably know this, but just wanted to point this out for the asker) – JNYRanger Jun 09 '15 at 12:52
  • Expanded a bit. Thanks :) – xlecoustillier Jun 09 '15 at 12:55
1

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.

0

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.

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48