条件OR运算符的短路行为(||) [英] short-circuiting behavior of conditional OR operator(||)
问题描述
有条件的算子和&&和||按照
进行短路 http:// docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html ,这意味着有时不需要评估第二个操作数。
Both conditional operators && and || are short-circuited as per
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html, which means the second operand does not need to be evaluated at times.
有人可以提供一个示例,其中条件OR(||)运算符会被短路吗?
短路行为使用条件AND(&&)运算符非常简单:
Short-circuiting behavior is pretty straightforward with the conditional-AND(&&) operator as in:
if(false&&(1> 0))然后是第二个操作数:(1> 0)不需要进行评估,但似乎无法找到/想到条件OR的示例。
if(false && (1 > 0)) then the second operand:(1 >0) would not need to be evaluated but can't seem to find/think of an example for conditional-OR.
推荐答案
当第一个操作数为真时,或运算符被短路。所以,
The or operator is short-circuited when the first operand is true. So,
String foo = null;
if (true || foo.equals("")) {
// ...
}
不会抛出 NullPointerException
。
正如@prajeesh正确在评论中指出,在实际代码中使用短路的方法是在处理可能返回null的API时阻止 NullPointerException
。因此,例如,如果有一个 readStringFromConsole
方法返回当前可用的字符串,或者如果用户没有输入任何内容,则返回null,我们可以写
As @prajeesh rightly points out in the comments, on way that short-circuiting is used in real code is to prevent a NullPointerException
whenever you are dealing with an API that might return null. So, for instance, if there is a readStringFromConsole
method that returns either the currently available string or null if the user doesn't type anything, we could write
String username = readStringFromConsole();
while (username == null || username.length() == 0) {
// No NullPointerException on the while clause because the length() call
// will only be made if username is not null
System.out.println("Please enter a non-blank name");
username = readStringFromConsole();
}
// Now do something useful with username, which is non-null and of nonzero length
作为旁注,返回用户输入的API应该在用户没有输入任何内容时返回空字符串,并且不应返回null。返回null是一种说没有任何可用的方式,而返回空字符串是一种说用户没有输入任何内容的方式,因此是首选。
As a side note, an API that returns user input should return the empty string whenever the user doesn't type anything, and shouldn't return null. Returning null is a way of saying "there is nothing available," while returning the empty string is a way of saying "the user didn't type anything" and so is preferred.
这篇关于条件OR运算符的短路行为(||)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!