5

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?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80

2 Answers2

6

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Just to extend the above accepted answer which is to the point but you may as well avoid casting here.

   Double value = null;
   Double v = value != null && value.isNaN() ? Double.valueOf(0.0) : value;
   System.out.println(v);

The Double.valueOf(0.0) will provide a Double in first type of condition which will make the conditional operator to evaluate into the type of Double since value is as well of type Double. So if no participant of condition is of primitive type double, it will not try any unboxing and a NPE will not be thrown.

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47