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)
JLS section 15.25 has a table that summarizes the type of the conditional expression based on the type of its operands. For the case of
Integer
andDouble
, the table says that the type will be the result of applying binary numeric promotion to the arguments (§15.25.2)Quoting binary numeric promotion:
This is what's happening for
new Integer(1)
is unboxed to the primitiveint
1.new Double(2.0)
is unboxed to the primitivedouble
2.0.double
. In this case, sinceboo
istrue
, the primitiveint
1 will be promoted todouble
as 1.0.Object
, the primitive result is boxed into its wrapper type.For the case of
the if/else construct does not perform numeric promotion. In fact there won't be any boxing conversion. Since
boo
istrue
, theif
part will be executed andobject2
will have the valuenew Integer(1)
.