[英]Why do I get a NPE after assigning an Integer variable with value null to an int variable?
I want to know how the compiler reads this code. 我想知道编译器如何读取此代码。
public class obj {
public static void main(String[] args) {
Integer obj = null; //line4
int x = obj; //line 5
System.out.println(x); //line6
}
}
My understanding is that line 5 can do auto unboxing which means it converts the Integer
type to primitive int
. 我的理解是,第5行可以进行自动拆箱,这意味着它将
Integer
类型转换为基本int
。
But I am not calling any method on x
, just printing. 但是我没有在
x
上调用任何方法,只是在打印。 Why is it giving me a NullPointerException
?. 为什么给我一个
NullPointerException
?。
Autoboxing here means that 这里的自动装箱意味着
int x = obj;
is actually: 实际上是:
int x = obj.intValue();
and hence the NullPointerException, as obj is null. 因此是NullPointerException,因为obj为null。
Java有一种称为自动装箱的东西,其中Integer对象会自动转换为int原始类型。
看一下字节码
javap -c com.interviews.practise.obj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.