Can anyone tell me why does Java throw a NullPointerException
here?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
- The method
getSomeFloat
returnsFloat
. - Changing
0.0f
tonew Float(0)
works fine.
Can anyone tell me why does Java throw a NullPointerException
here?
Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
getSomeFloat
returns Float
.0.0f
to new Float(0)
works fine.The type of this ternary operator is float
. Therefore, if myObject.getSomeFloat()
returns null, a NullPointerException
is thrown when <some condition>
is true and myObject.getSomeFloat().floatValue()
is called in order to convert the Float
to float
.
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.
In your case, you have a primitive type - float - and the Boxed version of that float - Float. Therefore, the type of the conditional expression is the primitive type - float.