Type conversion when using the ternary operator

What is the type of val in the following code?

boolean asInt = true;
Object val = asInt? 5 : 5.0;

If you guessed Integer, guess again. :)

JLS states –

if the second and third operands have numeric type, …. binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

If the second and third operands are of different reference types, then it must be possible to convert one of the types to the other type (call this latter type T) by assignment conversion ; the type of the conditional expression is T.

(Ref – JLS 15.25 Conditional Operator ? : )

I am sure I would have come across this while studying for my SCJP exam, but in real life, you rarely have objects of different types being returned from a ternary operator, so this can really catch you unguarded.

With an If-Else block, things work out as expected –

boolean asInt = true;
Object val = asInt? 5 : 5.0;
System.out.println("val is - " + val + " : " + val.getClass());
if (asInt) val = 5;
else val = 5.0;
System.out.println("val is - " + val + " : " + val.getClass());