代码编译正常,但 JVM 抛出 NullPointerException
code compiles fine, but the JVM throws a NullPointerException
class Boxing2 {
static Integer x;
public static void main(String[] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
}
}
此代码编译正常,但 JVM 抛出 NullPointerException
Exception in thread "main" java.lang.NullPointerException at
Boxing2.main(Test.java:4)
我想不通这是什么原因。
x
字段是null
,所以null
传递给doStuff
方法的x
参数,
因此自动装箱 null
到 int
类型抛出 NullPointerException
.
Integer
默认为 null
,而 int
默认为 0
.
class Boxing2 {
static Integer x;
public static void main(String[] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
}
}
此代码编译正常,但 JVM 抛出 NullPointerException
Exception in thread "main" java.lang.NullPointerException at Boxing2.main(Test.java:4)
我想不通这是什么原因。
x
字段是null
,所以null
传递给doStuff
方法的x
参数,
因此自动装箱 null
到 int
类型抛出 NullPointerException
.
Integer
默认为 null
,而 int
默认为 0
.