In the following inline conditionals, one might expect an integer and a double to be printed, respectively:
System.out.println(true ? 0 : 0.0);
System.out.println(false ? 0 : 0.0);
System.out.println(true ? new Integer(0) : new Double(0.0));
System.out.println(true ? 0 : "");
Instead they are both printed as doubles when occurring together:
0.0
0.0
0.0
0
Why are numbers auto-cast when occurring with other numbers in inline conditionals?
Edit: If this is occurring because System.out.println is overloaded what is the case for:
list.add(true ? 0 : 0.0);
list.add(false ? 0 : 0.0);
list.add(true ? new Integer(0) : new Double(0.0));
list.add(true ? 0 : "");
System.out.println(list);
outputs:
[0.0, 0.0, 0.0, 0]
The conditional expression has to have a single result type, and that type is used to determine which overload of
System.out.printlnto use. Overloads are always determined at compile-time, and it would be really awkward for the compiler to take two completely separate paths for an expression depending on which condition was picked.If you want to do two different things based on a condition, use an
if. If you want to pick between two values, with one result type, based on a condition, then the conditional operator is perfect.EDIT: The interesting case here, IMO, is the third one. The compiler could have chosen to not perform any conversions, and just call
println(Object). To show that it’s not doing that, here’s a separate test:This prints out
class java.lang.Double– and if you look at the bytecode, you’ll see it’s unboxing theintthen reboxing it as aDouble. For the gory details of how it’s all determined, see section 15.25 of the JLS.