The ternary operator has a constant return type.
From JLS, section 15.25 :
Otherwise, binary numeric promotion (ยง5.6.2) is used for operand types, and the conditional expression type is the advanced type of the second and third operands.
Does that mean in (true) ? (int)2.5 : 3.5 (true) ? (int)2.5 : 3.5 , 2.5 converts to int (rounds down) and then expands to double .
In (true) ? (int)2.5 : 3 (true) ? (int)2.5 : 3 , int does not need to be expanded to double , because the other side is also int .
Finally, in (true) ? (int)2.5 + "" : 3.5); (true) ? (int)2.5 + "" : 3.5); it cannot be expanded since it is already converted to String .
source share