将短路运算符与其他运算符混合

Mixing short-circuit operators with other operators

假设以下表达式:

public class OperatorTest {

public static void main(String[] args) {
    int x = 0;
    int y = 0;

    if(0 == 0 || ++y == 1) {
        // Some other logic here
    }

    System.out.println(y);
}

}

输出为0。我了解短路运算符,因为||的右侧不会执行,因为左侧的计算结果为真。但是,++ 优先于短路逻辑运算符,所以 ++ 运算符不应该在计算逻辑运算符之前计算吗?注意:我可能不需要在现实世界中这样做;这是我正在学习的认证考试。

更高优先级的运算符更紧密地保留它们的参数,就好像存在括号一样。您的代码等同于:

public static void main (String[] args)
{
    int x = 0;
    int y = 0;

    if (0 == 0)
    {
        // Some other logic here
    }
    else if (++y == 1)
    {
        // Some other logic here
    }
    System.out.println (y);
} 

短路逻辑运算符在短路时甚至不计算右侧。这由 JLS, Section 15.24 涵盖,后者涵盖 || 运算符。

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

(大胆强调我的)

因此,++y 永远不会被评估,y 仍然是 0

当左侧的计算结果为 false 时,&& 运算符存在相同的短路行为。