代码编译正常,但 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参数, 因此自动装箱 nullint 类型抛出 NullPointerException.


Integer 默认为 null,而 int 默认为 0.