java Java中布尔表达式的求值顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2028653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean expression order of evaluation in Java?
提问by daveslab
Suppose I have the following expression
假设我有以下表达式
String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}
Eclipse warns me that myStringmight 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?
Eclipse 警告我myString布尔表达式的第二个短语中可能为空。但是,我知道有些编译器会在第一个条件失败时完全退出布尔表达式。Java 是这样吗?还是不保证评估顺序?
回答by Prasoon Saurav
However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?
但是,我知道有些编译器会在第一个条件失败时完全退出布尔表达式。Java 是这样吗?
Yes, that is known as Short-Circuit evaluation.Operators like &&and ||are operators that perform such operations.
是的,这就是所谓的短路评估。运营商喜欢&&并且||是执行此类操作的运营商。
Or is the order of evaluation not guaranteed?
还是不保证评估顺序?
No,the order of evaluation is guaranteed(from left to right)
不,评估顺序是有保证的(从左到右)
回答by Ed Altorfer
Java should be evaluating your statements from left to right. It uses a mechanism known as short-circuit evaluationto prevent the second, third, and nth conditions from being tested if the first is false.
Java 应该从左到右评估您的语句。它使用一种称为短路评估的机制来防止在第一个条件为假时测试第二个、第三个和第 n 个条件。
So, if your expression is myContainer != null && myContainer.Contains(myObject)and myContaineris null, the second condition, myContainer.Contains(myObject)will not be evaluated.
因此,如果您的表达式是myContainer != null && myContainer.Contains(myObject)并且myContainer为空,myContainer.Contains(myObject)则不会评估第二个条件。
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.
编辑:正如其他人提到的,特别是 Java 确实有用于布尔条件的短路和非短路运算符。使用&&会触发短路评估,&不会。
回答by danben
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 &.
詹姆斯和埃德是正确的。如果您遇到这样一种情况,即无论先前的失败条件如何,您都希望对所有表达式进行求值,则可以使用非短路布尔运算符&。
回答by James B
Yes, Java practices lazy evaluation of if statements in this way. if myString==null, the rest of the if statement will not be evaluated
是的,Java 以这种方式对 if 语句进行惰性求值。如果 myString==null,则不会评估 if 语句的其余部分

