I had this piece of code in my application (simplified version):
Object result; if (check) result = new Integer(1); else result = new Double(1.0); System.out.println(result); return result;
Then I decided to refactor the if-else statement to a ternary conditional expression so my code is more concise:
Object result = check ? new Integer(1) : new Double(1.0); System.out.println(result); return result;
It turned out that in case check is true
the two versions print different results:
1
or:
1.0
Isn't the ternary conditional equivalent to the corresponding if-else?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.
The ternary operator takes three operands, hence, the name ternary operator. It is also known as a conditional operator.
The if/else and the conditional (ternary) expression are not quite equivalent. The result of the conditional expression must have a type.
You're observing the effects of numeric type promotion (or type coercion).
Here's an excerpt from the language spec (see here), from the section describing the return value of the conditional expression:
Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
The final such case is (I've omitted the other cases here):
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
Here's the additional spec related to binary numeric promotion:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type double, the other is converted to double.
It's the first case (following cases omitted). double
always wins.
So regardless of the order of the 2nd and 3rd operands in your conditional expression, the return type of the expression will be promoted to double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With