In auto boxing, is the conversion based on the variable/reference that we assign to or the other way around?

StackOverflow https://stackoverflow.com/questions/17325165

  •  01-06-2022
  •  | 
  •  

Question

public class TestBox {
    Integer i;
    int j;

    public static void main (String[] args) {
        TestBox t = new TestBox();
        t.go();
    }

    public void go() {
        j = i;
        System.out.println(j);
        System.out.println(i);
    }
}  

I get a null pointer exception on line j=i.
Although if this line is transformed as i=j i get the out put as 0 0 which is the default values of int.
My question is, when i is assigned to j , shouldn't i get unboxed as an int variable and take the default value of 0 instead of its original default null ?

Was it helpful?

Solution 2

From JLS §5.1.8:

At run time, unboxing conversion proceeds as follows:

  • If r is null, unboxing conversion throws a NullPointerException

To avoid NPE, you need to initialize i (an Integer) before you try to assign it to a primitive

OTHER TIPS

Compiler translates this assignment

j = i;

... into this:

j = i.intValue( );

If i is null, you get NPE.

Because there is no equivalent of null in primitives. When you try to unbox i which is null to primitive j , it will be a NullPointerException as i is null. Unboxing null always throws NullPointerException. This is as per the JLS

If r is null, unboxing conversion throws a NullPointerException

You never initialized i, then i is null and no unboxing could be done on it.

initialize i with some values like

Integer i = someValue;

Your Integer i is not initialized. If you use eclipse that will show a error

Zero is defined as the default value of a primitive integer instance variable, and this is the only context where this default applies. It would be quite unsafe to assume zero out of thin air for a null-Integer value. Wisely, Java designers did not define it that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top