I was toying around with java, and I noticed something. It can be best shown here:
boolean boo = true;
Object object1 = boo ? new Integer(1) : new Double(2.0);
Object object2;
if (boo)
object2 = new Integer(1);
else
object2 = new Double(2.0);
System.out.println(object1);
System.out.println(object2);
I would expect the two to be the same, but this is what gets printed:
1.0
1
Does anyone have a good explanation for this?
A ternary must return the same type for both conditions, so your first result (
Integer) is promoted to a double to match2.0. See also,This is documented at JLS-15.25.2 - Numeric Conditional Expressions which reads (in part)