Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator, strange behavior [duplicate]

public static void main(String[] args) {
    Object o1;
    if (true)
        o1 = new Integer(5);
    else
        o1 = new Double(2.0);

    Object o2 = true ? new Integer(5) : new Double(2.0);

    System.out.println(o1);
    System.out.println(o2);
}

In the above sample code, by using the conditional operator (? :) I can rewrite the above example in a single line. So, I think the result of o1 & o2 must be the same. But, strangely, the result as below :

5
5.0

Could you guys please help me to point out why is this behaviour ?

UPDATED : The result will be the same with the following code:

Object o2 = true ? (Object) new Integer(5) : new Double(2.0);
like image 830
Phat H. VU Avatar asked Dec 04 '14 03:12

Phat H. VU


1 Answers

This appears to be a side effect of Autoboxing. The ? operator attempts to determine which is the base type that can be applied to Object. It sees Double on the right, and Integer, which can be autoboxed to Double as well.

Maybe it does this because Integer can be boxed to Double, but Double can not be boxed to Integer?

Note that this produces the same result...

Object o2 = true ? 5 : new Double(2.0);
like image 73
slipperyseal Avatar answered Oct 13 '22 11:10

slipperyseal