奇怪的Java行为。三元运算符 [英] Strange Java behaviour. Ternary operator
问题描述
为什么这段代码有效?
Float testFloat = null;
Float f = true ? null : 0f;
为什么抛出异常?
Float testFloat = null;
Float f = true ? testFloat : 0f;
但最奇怪的是,此代码也成功运行,没有任何例外:
But the strangest thing is that this code also runs successfully without any exceptions:
Float testFloat = null;
Float f = testFloat;
似乎Java的三元运算符改变了行为。任何人都可以解释为什么会这样吗?
It seems that the ternary operator of Java changes the behaviour. Can anyone explain why this is, please?
推荐答案
行为在 JLS - 有条件运营商:
如果第二个和第三个操作数之一是原始类型T,而另一个操作数的类型是将装箱转换(第5.1.7节)应用于T的结果,那么条件表达式的类型是T 。
强调我的。那么,在2 nd 的情况下:
Emphasis mine. So, in the 2nd case:
Float f = true ? testFloat : 0f;
由于第3个操作数是原始类型( T
),表达式的类型是float类型 - T
。因此,取消装箱 testFloat 目前是 null
引用, float
将导致 NPE 。
Since 3rd operand is primitive type(T
), the type of the expression would be float type - T
. So, unboxing testFloat which is currently a null
reference, to float
will result in NPE.
至于1 st 情况,相关部分是最后一个:
As for the 1st case, relevant part is the last one:
否则,第二个和第三个操作数分别为S1和S2类型。设T1是将拳击转换应用到S1所产生的类型,让T2为应用到S2的装箱转换所产生的类型。条件表达式的类型是将捕获转换(第5.1.10节)应用于lub(T1,T2)(第15.12.2.7节)的结果。
Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).
所以,根据这个:
null type - S1
float - S2
null type - T1 (boxing null type gives null type)
Float - T2 (float boxed to Float)
然后条件表达式的类型变为 - Float
。不需要取消装箱 null
,因此没有 NPE
。
and then type of conditional expression becomes - Float
. No unboxing of null
needed, and hence no NPE
.
这篇关于奇怪的Java行为。三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!