当 Java 计算一个连词 (<boolean exp1> && <boolean exp2>) 时,如果 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.

相关文章