java 运算符优先级 DOT 与逻辑 AND

标签 java operator-precedence

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/

相关文章:

c++ - C++17 引入的评估顺序保证是什么?

c - gcc 中是否有针对 "i=i--"行为的特定文档?

java - 使用 restTemplate 时线程被阻塞

java - JVM 总是会创建 Object 类的实例吗

java - Spring维护数据一致性

java - 如何检查 Selenium 中面包屑的顺序

c++ - 对同一对象的链接操作和求值顺序

java - Android 编辑文本 : Check if whitespace not at beginning or end

php - 或 偏好随着返回而改变

c - 后缀增量运算符评估