Null Integer object assigned to primitive int throws NullPointerException

我的梦境 提交于 2019-12-01 13:34:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!