问题描述
为什么这段代码有效?
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?
推荐答案
行为在:
强调我的。那么,在2 的情况下:
Emphasis mine. So, in the 2 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 情况,相关部分是最后一个:
As for the 1 case, relevant part is the last one:
所以,根据这个:
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行为。三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!