Java中布尔表达式求值顺序?

发布于 2024-08-16 21:52:42 字数 288 浏览 6 评论 0原文

假设我有以下表达式,

String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}

Eclipse 警告我布尔表达式的第二个短语中的 myString 可能为 null。但是,我知道如果第一个条件失败,某些编译器将完全退出布尔表达式。 Java 也是这样吗?或者评估顺序无法保证?

Suppose I have the following expression

String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}

Eclipse warns me that myString might be null in the second phrase of the boolean expression. However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java? Or is the order of evaluation not guaranteed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

今天小雨转甜 2024-08-23 21:52:42

但是,我知道如果第一个条件失败,某些编译器将完全退出布尔表达式。 Java 也是这样吗?

是的,这就是所谓的短路评估。类似 && 的运算符;|| 是执行此类操作的运算符。

或者评估顺序无法保证?

不,保证评估顺序(从左到右)

However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?

Yes, that is known as Short-Circuit evaluation.Operators like && and || are operators that perform such operations.

Or is the order of evaluation not guaranteed?

No,the order of evaluation is guaranteed(from left to right)

小红帽 2024-08-23 21:52:42

Java 应该从左到右评估你的语句。它使用一种称为短路评估的机制来防止第二个、第三个和第n个如果第一个条件为假,则条件不被测试。

因此,如果您的表达式为 myContainer != null && myContainer.Contains(myObject)myContainer 为 null,则不会评估第二个条件 myContainer.Contains(myObject)

编辑:正如其他人提到的,Java 特别具有用于布尔条件的短路和非短路运算符。使用 && 将触发短路评估,而 & 则不会。

Java should be evaluating your statements from left to right. It uses a mechanism known as short-circuit evaluation to prevent the second, third, and nth conditions from being tested if the first is false.

So, if your expression is myContainer != null && myContainer.Contains(myObject) and myContainer is null, the second condition, myContainer.Contains(myObject) will not be evaluated.

Edit: As someone else mentioned, Java in particular does have both short-circuit and non-short-circuit operators for boolean conditions. Using && will trigger short-circuit evaluation, and & will not.

_失温 2024-08-23 21:52:42

詹姆斯和艾德是正确的。如果您希望对所有表达式进行求值,而不管之前的失败条件如何,则可以使用非短路布尔运算符 &

James and Ed are correct. If you come across a case in which you would like all expressions to be evaluated regardless of previous failed conditions, you can use the non-short-circuiting boolean operator &.

花开雨落又逢春i 2024-08-23 21:52:42

是的,Java 采用这种方式对 if 语句进行惰性求值。如果 myString==null,则 if 语句的其余部分将不会被计算

Yes, Java practices lazy evaluation of if statements in this way. if myString==null, the rest of the if statement will not be evaluated

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文