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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With