java - Java 中的三元运算符仅评估自 Java 7 以来的一个表达式 - 在 Java 1.6 及更低版本中是否有所不同?

标签 java ternary-operator java-6 short-circuiting

在准备 Oracle Certified Associate Java SE 8 Programmer 1 考试时,我在官方学习指南中看到了以下关于三元表达式的段落:

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: [...]

它表示只计算两个表达式中的一个,用下面的例子演示:

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

这里,只有 y 递增,但 z 不会,如您所料。

我偶然发现的是段落的开头(标记为黄色),它说“从 Java 7 开始,......”。我用 Java 1.6 测试了相同的代码,但我找不到行为上的差异。我希望 Java 1.6 仅根据段落中给出的信息来评估这两个表达式。有谁知道他们想用“从 Java 7 开始,...”说什么?

编辑: 为避免混淆:归结为一个问题,因为他们写的是“从 Java 7 开始”,当从 Java 6 切换到 Java 时,三元运算符是否有任何变化7?

最佳答案

来自 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.

类似的措辞也出现在可追溯到 1.0 的 JLS 版本中。 . Java 7 中的行为没有改变;学习指南措辞不佳。

关于java - Java 中的三元运算符仅评估自 Java 7 以来的一个表达式 - 在 Java 1.6 及更低版本中是否有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29557106/

相关文章:

java - 为什么这段代码会导致 JVM 崩溃?

java - java.util.spi包有什么用?

java - 从数据库中获取年份

java - 编译错误: java. lang.UnsatisfiedLinkError : no J3D in java.library.path

java - 如何找到引用方法的第一个声明方法

C# ? : operator

java - 是否可以使用 Java 注释来更改方法可见性?

php - 使用三元运算符的 echo 中的 if 语句

Javascript 到 PHP else if ": ?"运算符转换

android - Gradle同步失败: Cause: failed to find target with hash string 'android-22'