Why does this code work?
Float testFloat = null;
Float f = true ? null : 0f;
And why does this throw an exception?
Float testFloat = null;
Float f = true ? testFloat : 0f;
But the strangest thing is that this code also runs successfully without any exceptions:
Float testFloat = null;
Float f = testFloat;
It seems that the ternary operator of Java changes the behaviour. Can anyone explain why this is, please?
The behaviour is specified in JLS - Conditional Operator:
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) to T, then the type of the conditional expression is T.
Emphasis mine. So, in the 2nd case:
Float f = true ? testFloat : 0f;
Since 3rd operand is primitive type(T
), the type of the expression would be float type - T
. So, unboxing testFloat which is currently a null
reference, to float
will result in NPE.
As for the 1st case, relevant part is the last one:
Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).
So, according to this:
null type - S1
float - S2
null type - T1 (boxing null type gives null type)
Float - T2 (float boxed to Float)
and then type of conditional expression becomes - Float
. No unboxing of null
needed, and hence no NPE
.
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