问题描述
请你运行以下并解释一下吗?
Can you please run the below and explain?
Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);
我发现令人惊讶的是,有人预计会打印1而不是1.0
I found that surprising as someone would expect 1 to be printed and not 1.0
推荐答案
这一点都不奇怪,虽然它看起来像是一个。该行为在:
It's not a surprise at all, although it might seem like one. The behaviour is specified in JLS §15.25 - Conditional Operator:
-
如果其中一个操作数的类型为
byte
或字节
,另一个是
类型short
或短
,然后条件表达式的类型是
short
。
If one of the operands is of type
byte
orByte
and the other is of typeshort
orShort
, then the type of the conditional expression isshort
.
[...]
否则,二进制数字促销(§5.6.2)将应用于操作数
类型,条件表达式的类型是第二个和第三个操作数的提升类型
。
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
所以整数
和 Double
类型被拆箱到各自的原始对应物 - int
和 double
,作为二进制数字促销的过程。然后条件运算符的类型是 int
和 double
的提升类型,即双
。因此结果是 1.0
。当然最终的结果会被装回 Double
。
So the Integer
and Double
types are unboxed to their respective primitive counterparts - int
and double
, as a process of binary numeric promotion. And then the type of the conditional operator is the promoted type of int
and double
, which is double
. Hence the result is 1.0
. And of course the final result is then boxed back to Double
.
这篇关于使用条件运算符的奇怪java行为。这是一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!