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?
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
