NullPointerException with autoboxing in ternary expression

Alexander picture Alexander · Jul 16, 2010 · Viewed 6.9k times · Source

Run the following Java code:

boolean b = false;
Double d1 = 0d;
Double d2 = null;
Double d = b ? d1.doubleValue() : d2;

Why is there a NullPointerException?

Answer

Justin Ardini picture Justin Ardini · Jul 16, 2010

The return type of the conditional expression b ? d1.doubleValue : d2 is double. A conditional expression must have a single return type. Following the rules for binary numeric promotion, d2 is autounboxed to a double, which causes a NullPointerException when d2 == null.

From the language spec, section §15.25:

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases: ...

Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).