Unexpected NullPointerException while autoboxing / unboxing java Long type as return value

238 Views Asked by At

Can somebody explain why the getY() method causing NullPointerException.

public class NullTest {
    private String s = "";

    public Long getValue() {
        return null;
    }

    public Long getX() {
        return s != null ? getValue() : new Long(0);
    }

    public Long getY() {
        return s != null ? getValue() : 0L;
    }

    public static void main(String[] args) {
        NullTest nt = new NullTest();
        System.out.println("x = " + nt.getX());
        System.out.println("y = " + nt.getY());
    }
}

Sample output:

x = null
Exception in thread "main" java.lang.NullPointerException
    at NullTest.getY(NullTest.java:13)
    at NullTest.main(NullTest.java:19)
1

There are 1 best solutions below

2
Eran On

The type of the expression s != null ? getValue() : 0L is long, not Long. Therefore, if s != null is true and getValue() is null, a NullPointerExcetpion is thrown when trying to unbox that null to long.

You don't get this issue in getX(), since in the expression s != null ? getValue() : new Long(0), both getValue() and new Long(0) are Long, so the type of the expression is Long, and no unboxing takes place.