Ternary operator in Java only evaluating one expression since Java 7 - was that different in Java 1.6 and lower?
Preparing for the Oracle Certified Associate Java SE 8 Programmer 1 exam, I came across the following paragraph about the ternary expression in the official Study Guide:
Ternary Expression Evaluation
As of Java 7, only one of the right-hand expressions of the ternary operator will be evaluated at runtime. In a manner similar to the short-circuit operators, if one of the two right-hand expressions in a ternary operator performs a side effect, then it may not be applied at runtime. Let's illustrate this principle with the following example: [...]
It says that only one of the two expressions is evaluated, demonstrating with the following example:
int y = 1;
int z = 1;
int a = y < 10 ? y++ : z++;
Here, only y
increments, but z
does not, as you would expect.
What I am stumbling across is the beginning of the paragraph (marked in yellow) where it says "As of Java 7, ...". I tested the same code with Java 1.6 and I can't find a difference in the behavior. I expected Java 1.6 to evaluate both expressions just from the information given in the paragraph. Does anyone have an idea what they wanted to say with "As of Java 7, ..."?
Edit: To avoid confusion: It boils down to the question, Since they write 'As of Java 7', was there anything that changed concerning the ternary operator, when switching from Java 6 to Java 7?
Solution 1:
From the Java 6 JLS:
At run time, the first operand expression of the conditional expression is evaluated first; if necessary, unboxing conversion is performed on the result; the resulting boolean value is then used to choose either the second or the third operand expression:
- If the value of the first operand is true, then the second operand expression is chosen.
- If the value of the first operand is false, then the third operand expression is chosen.
The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. This conversion may include boxing (§5.1.7) or unboxing conversion. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
Similar wording also appears in JLS editions going back to 1.0. The behavior didn't change in Java 7; the study guide is just poorly worded.
Solution 2:
I'm one of the authors of the book this came from. While I didn't write that particular sentence, I agree the intent was "this was tested on Java 7". I'll make a note to remove that if we write another edition.
To be clear, the ternary operator has behaved the same way in Java 8, 7, 6, etc. And I'd be quite surprised if it changed in the future.