boolean a = false;
boolean b = false;
boolean c = false;
boolean bool = (a = true) || (b = true) && (c = true);
System.out.println("" + a + b + c);
前面的代码打印truefalsefalse
。但是,&&
运算符的优先级高于 ||
运算符,应该先求值,那么为什么它不打印 truetruetrue
?
最佳答案
我相信您问题的症结在于这部分:
But, the && operator has higher precedence than the || operator and should be evaluated first
没有。优先级不影响执行顺序。它有效地包围了。所以你的表达等同于:
boolean bool = (a = true) || ((b = true) && (c = true));
... 仍然首先执行 a = true
。到那时,由于结果肯定是true
并且||
是短路的,所以||
的右操作数不是已执行,所以 b
和 c
为 false。
来自 JLS section 15.7.1 :
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
优先级与此无关。
关于使用 AND 和 OR 的 Java 表达式评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272198/