Java中布尔表达式求值顺序?
假设我有以下表达式,
String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}
Eclipse 警告我布尔表达式的第二个短语中的 myString
可能为 null。但是,我知道如果第一个条件失败,某些编译器将完全退出布尔表达式。 Java 也是这样吗?或者评估顺序无法保证?
Suppose I have the following expression
String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}
Eclipse warns me that myString
might be null in the second phrase of the boolean expression. However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java? Or is the order of evaluation not guaranteed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这就是所谓的短路评估。类似
&& 的运算符;
和||
是执行此类操作的运算符。不,保证评估顺序(从左到右)
Yes, that is known as Short-Circuit evaluation.Operators like
&&
and||
are operators that perform such operations.No,the order of evaluation is guaranteed(from left to right)
Java 应该从左到右评估你的语句。它使用一种称为短路评估的机制来防止第二个、第三个和第n个如果第一个条件为假,则条件不被测试。
因此,如果您的表达式为
myContainer != null && myContainer.Contains(myObject)
且myContainer
为 null,则不会评估第二个条件myContainer.Contains(myObject)
。编辑:正如其他人提到的,Java 特别具有用于布尔条件的短路和非短路运算符。使用
&&
将触发短路评估,而&
则不会。Java should be evaluating your statements from left to right. It uses a mechanism known as short-circuit evaluation to prevent the second, third, and nth conditions from being tested if the first is false.
So, if your expression is
myContainer != null && myContainer.Contains(myObject)
andmyContainer
is null, the second condition,myContainer.Contains(myObject)
will not be evaluated.Edit: As someone else mentioned, Java in particular does have both short-circuit and non-short-circuit operators for boolean conditions. Using
&&
will trigger short-circuit evaluation, and&
will not.詹姆斯和艾德是正确的。如果您希望对所有表达式进行求值,而不管之前的失败条件如何,则可以使用非短路布尔运算符
&
。James and Ed are correct. If you come across a case in which you would like all expressions to be evaluated regardless of previous failed conditions, you can use the non-short-circuiting boolean operator
&
.是的,Java 采用这种方式对 if 语句进行惰性求值。如果 myString==null,则 if 语句的其余部分将不会被计算
Yes, Java practices lazy evaluation of if statements in this way. if myString==null, the rest of the if statement will not be evaluated