问题
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.
回答1:
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
.
JLS 15.25:
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.
来源:https://stackoverflow.com/questions/27730895/strange-nullpointerexception-in-ternary-conditional-expression