Search code examples
javaconditional-expressions

Numeric Type Promotion with Conditional Expression


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?


Solution

  • A ternary must return the same type for both conditions, so your first result (Integer) is promoted to a double to match 2.0. See also,

    Object object1 = boo ? new Integer(1) : new Double(2.0);
    System.out.println(object1.getClass().getName());
    

    This is documented at JLS-15.25.2 - Numeric Conditional Expressions which reads (in part)

    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).