三元运算符中不需要的NullPointerException-为什么? [英] Unwanted NullPointerException in ternary operator - Why?
问题描述
在执行以下代码时,我在行中得到了 NullPointerException
:
While executing the following code, I am getting a NullPointerException
at line:
value = condition ? getDouble() : 1.0;
在前面的行中,我使用 null
代替 getDouble()
的所有方法都有效,这很奇怪。
In earlier lines when I use null
instead of getDouble()
everything works and this is strange.
public class Test {
static Double getDouble() {
return null;
}
public static void main(String[] args) {
boolean condition = true;
Double value;
value = condition ? null : 1.0; //works fine
System.out.println(value); //prints null
value = condition ? getDouble() : 1.0; //throws NPE
System.out.println(value);
}
}
有人可以帮助我了解这种行为吗?
Can someone help me understand this behavior?
推荐答案
写时
value = condition ? null : 1.0;
条件的类型? null:1.0
必须是引用类型,因此类型为 Double
,它可以容纳值 null
。
the type of condition ? null : 1.0
must be a reference type, so the type is Double
, which can hold the value null
.
书写时
value = condition ? getDouble() : 1.0;
和 getDouble()
返回 null
,等效于编写:
value = condition ? ((Double) null) : 1.0;
在这种情况下,编译器会看到 Double
和 double
作为三元条件运算符的第二个和第三个参数,并确定表达式的类型应为 double
。因此,它将 null
拆箱为 double
,得到 NullPointerException
。
In this case the compiler sees a Double
and a double
as the 2nd and 3rd arguments of the ternary conditional operator, and decides that type of the expression should be double
. Therefore it unboxes the null
to double
, getting NullPointerException
.
条件三元运算符的类型由 JLS 15.25 。
The type of the conditional ternary operator is determined by some tables in JLS 15.25.
如果第二和第三操作数小于code> null 和 double
,条件表达式类型是 Double $ c $的最小上限c>和
null
,即 Double
。
If the 2nd and 3rd operands are null
and double
, the conditional expression type is the least upper bound of Double
and null
, which is Double
.
如果第二和第三操作数为 Double
和 double
,则条件表达式类型为 double
。
If the 2nd and 3rd operands are Double
and double
, the conditional expression type is double
.
这篇关于三元运算符中不需要的NullPointerException-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!