Why does this work:
String a = null;
String b = a != null && a.equals("Nan") ? "Nan" : a;
System.out.println(b);
but this produces NPE:
Double value = null;
Double v = value != null && value.isNaN() ? 0.0 : value;
System.out.println(v);
Rewriting it as:
Double value = null;
Double v;
if (value != null && value.isNaN()) {
v = 0.0;
} else {
v = value;
}
of course works as expected. But why do I get NPE using the ternary/conditional operator when using Double
and no NPE when using String
? What am I missing?
The type of the conditional expression is inferred as double
, so you get a NullPointerException
when the program attempts to unbox value
(which is null
) as a primitive double
.
To make the expression have a Double
result (which can store null
), cast 0.0
to Double
.
Double v = value != null && value.isNaN() ? (Double) 0.0 : value
See §15.25.2. Numeric Conditional Expressions for more details.