三元运算符中不需要的 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
视为三元条件运算符的第二个和第三个参数,并决定表达式的类型应该是 <代码>双代码>.因此,它将 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.
如果第二个和第三个操作数是null
和double
,条件表达式类型是Double
和的最小上界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屋!