NullPointerException with autoboxing in ternary expression

Viewed 7316

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?

4 Answers

Return same type for both condition like below and you will get result.

boolean b = false;
Double d1 = 0d;
Double d2 = null;
Double d = b ? d1 : (Double)d2;
System.out.println(d);
Related