分配给原始int的Null Integer对象抛出NullPointerException [英] Null Integer object assigned to primitive int throws NullPointerException
本文介绍了分配给原始int的Null Integer对象抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Integer i = null;
int j = i;
System.out.println(j);
为什么抛出 NullPointerException
并且没有' t打印 j
的值为 0
?
Why does it throw NullPointerException
and doesn't print the value of j
as 0
?
推荐答案
整数
是一个对象。因此可以为空。
Integer
is an object. Therefore it is nullable.
Integer i = null;
是正确的。
<$ c另一方面,$ c> int 是原始值,因此不可为空。
int
, on the other hand, is a primitive value, therefore not nullable.
int j = i;
相当于
int j = null;
这是不正确的,并抛出 NullPointerException
。
which is incorrect, and throws a NullPointerException
.
感谢JNYRanger:
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);
按预期输出12。
这篇关于分配给原始int的Null Integer对象抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文