我只是想知道为什么我们通常在两个布尔值之间使用逻辑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

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


当前回答

|是位操作符。||是逻辑运算符。

一个会取两个比特或者它们。

一个人将决定真理(这个或那个)如果这个是真的或那个是真的,那么答案就是真的。

哦,该死的人回答这些问题很快。

其他回答

Java运营商

|是位或,||是逻辑或。

来看看:

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

|是位包含或

||为逻辑或

| is the binary or operator

|| is the logic or operator

逻辑||和&&只在必要时检查右边。|和&每次检查两边。

例如:

int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...

重写:

int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i != 10
...

另一个例子:

int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...

重写:

int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...

附注:Java有|=,但没有||=

必须使用||的一个例子是,当第一个表达式是测试第二个表达式是否会爆炸时。例:在以下情况下使用单个|可能导致NPE。

public static boolean isNotSet(String text) {
   return text == null || text.length() == 0;
}