Returning null as an int permitted with ternary operator but not if statement
The compiler interprets null
as a null reference to an Integer
, applies the autoboxing/unboxing rules for the conditional operator (as described in the Java Language Specification, 15.25), and moves happily on. This will generate a NullPointerException
at run time, which you can confirm by trying it.
I think, the Java compiler interprets true ? null : 0
as an Integer
expression, which can be implicitly converted to int
, possibly giving NullPointerException
.
For the second case, the expression null
is of the special null type see, so the code return null
makes type mismatch.
Actually, its all explained in the Java Language Specification.
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.
Therefore the "null" in your (true ? null : 0)
gets an int type and then is autoboxed to Integer.
Try something like this to verify this (true ? null : null)
and you will get the compiler error.