Java Numeric Promotion in Conditional Expression
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.
// A Java program to demonstrate that we should be careful // when replacing conditional operator with if else or vice // versa import java.io.*; class GFG { public static void main (String[] args) { // Expression 1 (using ?: ) // Automatic promotion in conditional expression Object o1 = true ? new Integer(4) : new Float(2.0); System.out.println(o1); // Expression 2 (Using if-else) // No promotion in if else statement Object o2; if (true) o2 = new Integer(4); else o2 = new Float(2.0); System.out.println(o2); } } |
Output:
4.0 4
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.
This article is contributed by Deepak Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java

