问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/30732398/null-integer-object-assigned-to-primitive-int-throws-nullpointerexception