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

混合的时候要小心。

其他回答

| is the binary or operator

|| is the logic or operator

它们之间的基本区别是|首先将值转换为二进制,然后执行按位或操作。同时,||不将数据转换为二进制,只是在其原始状态上执行or表达式。

int two = -2; int four = -4;
result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110

阅读更多信息:http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk

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

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

混合的时候要小心。

| =位或,|| =逻辑或

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

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

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