以下两个if块的内容都应该被执行:
if( booleanFunction() || otherBooleanFunction() ) {...}
if( booleanFunction() | otherBooleanFunction() ) {...}
那么使用 |
和使用 ||
有什么区别呢?
注:我已经查过了并找到了自己的答案,我在下面附上了。请随意纠正我或提出您自己的看法。肯定还有改进的空间!
以下两个if块的内容都应该被执行:
if( booleanFunction() || otherBooleanFunction() ) {...}
if( booleanFunction() | otherBooleanFunction() ) {...}
那么使用 |
和使用 ||
有什么区别呢?
注:我已经查过了并找到了自己的答案,我在下面附上了。请随意纠正我或提出您自己的看法。肯定还有改进的空间!
这两者有不同的用途。尽管在许多情况下(处理布尔值时)它们可能具有相同的效果,但重要的是要注意逻辑OR是短路操作,这意味着如果其第一个参数求值为true,则第二个参数将被留未求值。位运算符则会评估其两个参数。
类似地,逻辑AND也是短路操作,这意味着如果其第一个参数求值为false,则第二个参数将被留未求值。位运算符则不是。
您可以在此处查看其效果:
int x = 0;
int y = 1;
System.out.println(x+y == 1 || y/x == 1);
System.out.println(x+y == 1 | y/x == 1);
第一个打印语句能够正常工作并且返回true,因为第一个参数的计算结果为true,所以计算停止。第二个打印语句出错了,因为它不是短路运算,会遇到除以零的情况。
逻辑运算符用于布尔类型,位运算符用于比特类型。在这种情况下,效果将是相同的,但有两个区别:
以下是一些方便的代码来证明这一点:
public class OperatorTest {
public static void main(String[] args){
System.out.println("Logical Operator:");
if(sayAndReturn(true, "first") || sayAndReturn(true, "second")){
//doNothing
}
System.out.println("Bitwise Operator:");
if(sayAndReturn(true, "first") | sayAndReturn(true, "second")){
//doNothing
}
}
public static boolean sayAndReturn(boolean ret, String msg){
System.out.println(msg);
return ret;
}
}
对于程序员来说,只有一个区别。
booleanFunction() || otherBooleanFunction() 如果其中任意一个为true,则为true。同样地,booleanFunction() && otherBooleanFunction() 如果其中任意一个为false,则为false。因此,为什么要测试另一个呢?这就是逻辑运算符的作用。
但是按位运算符检查两个条件。这个概念的一个常见应用是:
if(someObject != null && someObject.somemethod())
&
代替&&
,那么你将等待一场灾难。不久你会遇到讨厌的NullPointerException错误...if( booleanFunction() || otherBooleanFunction() ) {...}
booleanFunction()
返回 true
,则不会执行 otherBooleanFunction()
。if( booleanFunction() | otherBooleanFunction() ) {...}
但在位运算符中,无论booleanFunction()
返回true
还是false
,两个函数booleanFunction()
和otherBooleanFunction()
都将被执行。