javaoperators

Java casting variable to Double when using ternary operator


If I using ternary operator to assign an Object variable with Double or Integer value, it being casted to double for some reason.

No matter what I do with order and condition of ternary operator parameters, it still be Double for some reason. Here's few examples:

final Object n = false ? Double.parseDouble("2") : Integer.parseInt("1"); 
System.out.println(n + " " + n.getClass()); // Output is "1.0 class java.lang.Double"
final Object n = false ? Integer.parseInt("1") : Double.parseDouble("2");
System.out.println(n + " " + n.getClass()); // Output is "2.0 class java.lang.Double"
final Object n = true ? Integer.parseInt("1") : Double.parseDouble("2");
System.out.println(n + " " + n.getClass()); // Output is "1.0 class java.lang.Double"
final Object n = true ? Integer.valueOf("1") : Double.valueOf("2");
System.out.println(n + " " + n.getClass()); // Output is "1.0 class java.lang.Double"

As you can see in the last example I've tried to use valueOf instead of parse*, which returns non-primitive types (so no reason to cast them to assign an Object var???), but result still be the same. The question is why java casting value exactly to Double, when it's definitely not relying on parameters order, which of those are chosen, and need of casting?


Solution

  • The type returned by the conditional operator is determined by the Java Specification depending on the second and third operands' types.

    In your first and third case the second operand is an int, the third a double. If you look at Table 15.25-B. Conditional expression type (Primitive 3rd operand, Part II) in the linked spec, the result of such a conditional operation is defined as bnp(int,double), which means it applies binary numeric promotion of an int result to double that then gets autoboxed to a Double since you're assigning the result to an Object.

    In your second and fourth case we have a Integer and a Double. Table 15.25-D. Conditional expression type (Reference 3rd operand, Part II) tells us that the return type is bnp(Integer,Double) so, again, a Double.