gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:08:38 25 4
gpt4 key购买 nike

if(fName != null && fName.isEmpty())

在这个 if 表达式中我们有 4 个运算符

1) . access object member
2) () invoke a method
3) != equality
4) && conditional AND

我已经按照优先顺序列出,并且都具有相同的关联性,即从左到右

那么为什么这个表达式按下面的顺序求值(据我所知)

1) !=
2) &&
3,4) . ()

最佳答案

逻辑与运算符 (&&) 被短路。这意味着只有当左操作数的计算结果为真时,右操作数才会被评估。

因此 fName != null 首先被评估。

如果为真,则接下来评估 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com