The conditional operator
? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
So, we expect the expression,
Object o1 = true ? new Integer(4) : new Float(2.0));
to be same as,
Object o2; if (true) o2 = new Integer(4); else o2 = new Float(2.0);
But the result of running the code gives an unexpected result.
According to Java Language Specification Section 15.25, the conditional operator will implement numeric type promotion if there are two different types as 2nd and 3rd operand. The rules of conversion are defined at Binary Numeric Promotion. Therefore, according to the rules given, If either operand is of type double, the other is converted to double and hence 4 becomes 4.0.
Whereas, the if/else construct does not perform numeric promotion and hence behaves as expected.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above