This is similar to java ternary conditions strange null pointer exception and java: weird NullPointerException in ternary operator (? : ) but not exactly the same question.
Consider this example with a Box and a Thing. Why is NullPointerException thrown, why is not autoboxing working on the primitive integer 1?
public class Box {
public Integer getHeight() {
return null;
}
}
public class Thing {
private Box box;
public void doThings() {
setBox(new Box());
try {
System.out.println(getBox() != null ? getBox().getHeight() : Integer.valueOf(1)); // works
System.out.println(getBox() != null ? null : 1); // works
System.out.println(getBox() != null ? getBox().getHeight() : 1); // throws NPE
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Box getBox() {
return box;
}
public void setBox(Box box) {
this.box = box;
}
}