Strange java behaviour with conditional operator. Is it a bug?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 04:16:34

问题


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


回答1:


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.




回答2:


Here is an article published in DZone yesterday talking about it:

Java auto unboxing gotcha

Funny enough, the example code looks similar...



来源:https://stackoverflow.com/questions/19293575/strange-java-behaviour-with-conditional-operator-is-it-a-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!