Strange java behaviour with conditional operator.

2019-02-13 05:46发布

问题:

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...