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)
The type of the expression
s != null ? getValue() : 0Lislong, notLong. Therefore, ifs != nullis true andgetValue()isnull, aNullPointerExcetpionis thrown when trying to unbox thatnulltolong.You don't get this issue in
getX(), since in the expressions != null ? getValue() : new Long(0), bothgetValue()andnew Long(0)areLong, so the type of the expression isLong, and no unboxing takes place.