用条件运算符编写java程序,使用条件运算符的奇怪java行为。这是一个错误吗?...
Can you please run the below and explain?
Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);
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:
Otherwise, if the second and third operands have types that are
convertible (§5.1.8) to numeric types, then there are several cases:
If one of the operands is of type byte or Byte and the other is of
type short or Short, then the type of the conditional expression is
short.
[...]
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.
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
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.
總結(jié)
以上是生活随笔為你收集整理的用条件运算符编写java程序,使用条件运算符的奇怪java行为。这是一个错误吗?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java抽样器处于非活动状态_Coden
- 下一篇: 各大科技公司上万人研究 AI,但他们仍然