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);
    }
}

This code compiles fine, but the JVM throws a NullPointerException

Exception in thread "main" java.lang.NullPointerException at Boxing2.main(Test.java:4)

I cannot figure out the reason of this.

Poorna Senani Gamage
  • 1,246
  • 2
  • 19
  • 30
  • 1
    `x` is null, so it can't be **boxed** into an `int` . You can only box things, you cant box nothing ;-) – GhostCat Jul 20 '18 at 12:34

1 Answers1

3

x field is null, so null is passed to doStuff method's x parameter, hence autoboxing null to int type throws NullPointerException.


Integer defaults to null, while int defaults to 0.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
Tyvrel
  • 198
  • 2
  • 10