How come this code compiles? I would have expected the compiler to complain about a "Type mismatch: cannot convert from null to boolean" but it doesn't. It just fails with a NullPointerException at runtime.
public static void main(String[] args) throws Exception {
System.out.println("this throws a NPE: " + whyIsThisPossible(1, 2));
}
private static boolean whyIsThisPossible(int a, int b) {
return a + b == 2 ? true : null;
}
Exception in thread "main" java.lang.NullPointerException
at FunkyMethodTest.whyIsThisPossible(FunkyMethodTest.java:10)
at FunkyMethodTest.main(FunkyMethodTest.java:5)*
Java considers the type of ternary expression to be boolean. The compiler treats null as Boolean, i.e. the result of applying a boxing conversion to the primitive type of boolean.
Here is the relevant portion of the language specification:
15.25 The type of a conditional expression is determined as follows:
...
- 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) toT, then the type of the conditional expression isT.
Language specification states that the boxing/unboxing conversion is applied when necessary to the operand chosen by the condition of the expression. That is what triggers the exception when the code tries to unbox a boolean from null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With