我只是想知道为什么我们通常在两个布尔值之间使用逻辑OR ||,而不是按位或|,尽管它们都工作得很好。

我的意思是,看看下面这些:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

我们可以用|代替||吗?&和&&也是一样。


当前回答

还要注意一个常见的陷阱:非惰性操作符优先于惰性操作符,因此:

boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c

混合的时候要小心。

其他回答

||是逻辑或运算符,|是位或运算符。

boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;
| is the binary or operator

|| is the logic or operator

|是位运算符:||是短路运算符——当一个元素为假时,它将不检查其他元素。

 if(something || someotherthing)
 if(something | someotherthing)

如果某个值为TRUE, ||将不会计算另一个值,而|可以。如果If语句中的变量实际上是函数调用,那么使用||可能会节省大量性能。

| =位或,|| =逻辑或

来看看:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

|是位包含或

||为逻辑或