Java 中的三元运算符自 Java 7以来只计算一个表达式——这在 Java 1.6及更低版本中是不同的吗?

为了准备 Oracle 认证的助理 Java SE 8程序员1考试,我在正式的学习指南中看到了以下关于三元表达式的段落:

三元表达式计算
在 Java7中,只有三元运算符的右表达式之一会在运行时求值。与短路运算符类似,如果三元运算符中的两个右表达式之一产生了副作用,那么它可能不会在运行时应用。让我们用下面的例子来说明这个原则: [ ... ]

它说两个表达式中只有一个被求值,用下面的例子演示:

int y = 1;
int z = 1;
int a = y < 10 ? y++ : z++;

在这里,只有 y增量,但是 z没有,正如您所期望的那样。

我偶然发现的是段落的开头(用黄色标记) ,其中写道“ As of Java7,...”。我用 Java 1.6测试了相同的代码,但是我没有发现它们的行为有什么不同。我期望 Java 1.6仅仅根据段落中给出的信息来计算这两个表达式。有没有人知道他们想说什么“ As of Java7,...”?

编辑: 为了避免混淆: 它归结为一个问题,因为他们写了‘ As of Java7’,当从 Java6切换到 Java7时,是否有任何关于三元运算符的改变?

8730 次浏览

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.

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.