if(fName != null && fName.isEmpty())
在此 if 表达式中,我们有 4 个运算符
1) . access object member
2) () invoke a method
3) != equality
4) && conditional AND
我已按优先级列出,并且全部具有相同的关联性,即从左到右
那么为什么这个表达式按以下顺序求值(据我所知)
1) !=
2) &&
3,4) . ()
最佳答案
逻辑 AND 运算符 (&&
) 短路。这意味着仅当左操作数的计算结果为 true 时才计算右操作数。
因此首先评估fName != null
。
如果为 true,则接下来评估 fName.isEmpty()
,最后评估 &&
运算符本身,因为在评估其之前无法评估它操作数。
以下是 JLS 的相关引用:
15.7:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
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.
15.7.2:
The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.
关于java 运算符优先级 DOT 与逻辑 AND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33033426/