当Java的评估连词(小于布尔表达式1&GT;&放大器;&安培;&LT;布尔EXP2&GT;),做它的eval EXP2如果EXP1是假的? [英] When Java evaluates a conjunction (<boolean exp1> && <boolean exp2>), does it eval exp2 if exp1 is false?
问题描述
如果它保证了在Java程序中,在结合右边的布尔前pression(以上EXP2)将不会被只要评为左侧的前pression(我想知道EXP1)结果为假。我不知道,因为我有一个前pression这样的:
如果(VAR = NULL&放大器;!&安培; var.some predicate())
// 做一点事
如果Java是不能保证阻止评估(VAR = NULL&放大器;!&安培; var.some predicate())
它看到后 VAR
为空,则可以尝试评估 var.some predicate()
这将抛出NullPointerException。
所以我的问题是,Java的保证一定的行为,当谈到这一点?或者,它会更安全写
如果(VAR!= NULL)
{
如果(var.some predicate())
// 做一点事
}
在Java语言规范的 15.23条件,而运营商和放大器;&安培; :
的
&放大器;&安培;
运营商就像&安培;
(§15.22.2),但评估其右边的操作数只有在其左侧操作数的值是true
块引用>因此,语言规范保证如果左侧是假你的前pression的右手侧将不进行评价。
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
If Java is not guaranteed to stop evaluating
(var != null && var.somePredicate())
after it sees thatvar
is null, then it may try to evaluatevar.somePredicate()
which would throw a NullPointerException.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 }
解决方案From the Java Language Specification, 15.23 Conditional-And Operator &&:
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的评估连词(小于布尔表达式1&GT;&放大器;&安培;&LT;布尔EXP2&GT;),做它的eval EXP2如果EXP1是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!