java - 三元条件表达式中出现奇怪的 NullPointerException

标签 java nullpointerexception conditional-statements

<分区>

谁能告诉我为什么 Java 会在此处抛出 NullPointerException

Float x = <some condition> ? myObject.getSomeFloat() : 0.0f;
  • 方法 getSomeFloat 返回 Float
  • 0.0f 更改为 new Float(0) 效果很好。

最佳答案

这个三元运算符的类型是float .因此,如果 myObject.getSomeFloat()返回 null,一个 NullPointerException<some condition> 时抛出是真的 myObject.getSomeFloat().floatValue()调用以转换 Floatfloat .

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.

在您的例子中,您有一个基本类型 - 浮点型 - 以及该浮点型的盒装版本 - 浮点型。因此,条件表达式的类型是原始类型——float。

关于java - 三元条件表达式中出现奇怪的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730895/

相关文章:

java - 为什么我在该对象上收到 NullPointerException?

java - 什么是NullPointerException,我该如何解决?

java - Lejos EV3 "Null Pointer Exception",但我不知道如何修复它

python - 基于已安装的模块编写条件语句的 Pythonic 方式是什么?

c++ - 如何有效地检查 10 个变量是否不同

java - Hazelcast 并行处理中故障转移的最佳实践

java - 为什么模拟的类不会进入未模拟的函数?

python - Django条件注释不带过滤

java - Android 从资源中获取颜色列表

java - 旅行推销员 - 如何找到不等价的排列