When Java evaluates a conjunction (lt;boolean exp1gt; amp;amp; lt;boolean exp2gt;), does it eval exp2 if exp1 is false?(当 Java 计算一个连词 (lt;boolean exp1gt; amp;amp; lt;boolean exp2gt;) 时,如果 exp1 为假,它是否评估 exp2?)
问题描述
我想知道是否可以保证在 Java 程序中,只要左侧的表达式 (exp1) 评估为 false,就不会评估连接右侧的布尔表达式(上面的 exp2).我想知道,因为我有如下表达式:
I'm wondering if it's guaranteed that in a Java program, the boolean expression on the right of a conjunction (exp2 above) will NOT be evaluated as long as the expression on the left (exp1) evaluated to false. I'm wondering because I have an expression like the following:
if (var != null && var.somePredicate())
// do something
如果 Java 在看到 var
为 null 后不能保证停止评估 (var != null && var.somePredicate())
,那么它可能会尝试评估会抛出 NullPointerException 的 var.somePredicate()
.
If Java is not guaranteed to stop evaluating (var != null && var.somePredicate())
after it sees that var
is null, then it may try to evaluate var.somePredicate()
which would throw a NullPointerException.
所以我的问题是,Java 在这方面是否保证某种行为?还是写起来更安全
So my question is, does Java guarantee a certain behavior when it comes to this? Or would it be safer to write
if (var != null)
{
if (var.somePredicate())
// do something
}
推荐答案
来自 Java 语言规范,15.23 条件与运算符&&:
From the Java Language Specification, 15.23 Conditional-And Operator &&:
&&
运算符类似于 &
(第 15.22.2 节),但 只有在左操作数为真.
The
&&
operator is like&
(§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
因此语言规范保证如果左侧为假,则不会计算表达式的右侧.
So the language spec guarantees that the right-hand side of your expression will not be evaluated if the left hand side is false.
这篇关于当 Java 计算一个连词 (<boolean exp1> && <boolean exp2>) 时,如果 exp1 为假,它是否评估 exp2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当 Java 计算一个连词 (<boolean exp1> && <boolean exp2>) 时,如果 exp1 为假,它是否评估 exp2?


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01