当Java的评估连词(小于布尔表达式1>&放大器;&安培;<布尔EXP2>),做它的eval EXP2如果EXP1是假的? [英] When Java evaluates a conjunction (<boolean exp1> && <boolean exp2>), does it eval exp2 if exp1 is false?

查看:162
本文介绍了当Java的评估连词(小于布尔表达式1>&放大器;&安培;<布尔EXP2>),做它的eval EXP2如果EXP1是假的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它保证了在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 that var is null, then it may try to evaluate var.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>&放大器;&安培;<布尔EXP2>),做它的eval EXP2如果EXP1是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆