Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 678
Dimitrios Douras Avatar asked Oct 10 '13 10:10

Dimitrios Douras


1 Answers

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.

like image 161
Rohit Jain Avatar answered Sep 30 '22 20:09

Rohit Jain