NullPointerException through auto-boxing-behavior of Java ternary operator
Solution 1:
According to JLS: -
The type of a conditional expression is determined as follows:
- If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
- If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion
(§5.1.7) to T, then the type of the conditional expression is T.
Solution 2:
The problem is that:
Integer number = (condition) ? getNumber() : 0;
Forces an unboxing and reboxing of the result of getNumber(). This is because the false part of the ternary (0) is an integer, so it tries to convert the result of getNumber() to an int. Whereas the following does not:
Integer number = (condition) ? getNumber() : (Integer) 0;
This is not a bug, just the way Java chose to do things.
Solution 3:
This is how it is supposed to work. The ternary operator is not meant to be equivalent to a regular if
statement. The bodies of if
and else
are statements, while the parts following ?
and :
are expressions, that are required to evaluate to the same type.
Put another way: a = b ? c : d
is not supposed to be equivalent to if (b) a = c; else a = d;
. Instead, b ? c : d
is an expression on its own, and the assignment of its result to a
won't affect the outcome.