简体   繁体   中英

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

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 .

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

Java auto unboxing gotcha

Funny enough, the example code looks similar...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM