Strange NullPointerException in ternary conditional expression [duplicate]

余生长醉 提交于 2020-01-16 05:11:46

问题


Can anyone tell me why does Java throw a NullPointerException here?

Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
  • The method getSomeFloat returns Float.
  • Changing 0.0f to new 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!