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

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


当前回答

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

其他回答

有很多用例表明为什么你应该选择||而不是|。有些用例必须使用|操作符来检查所有条件。

例如,如果您希望检查表单验证,并且希望向用户显示所有带有错误文本的无效字段,而不仅仅是第一个无效字段。

||算子是,

   if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

   private boolean checkIfEmpty(Widget field) {
      if(field.isEmpty()) {
        field.setErrorMessage("Should not be empty!");
        return true;
      }
      return false;
   }

因此,在上面的代码片段中,如果用户提交的表单中所有字段都是空的,那么只有nameField将显示错误消息。但是,如果你把它改成,

   if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

无论真实情况如何,它都会在每个字段上显示正确的错误信息。

A | b:在任何情况下计算b

A || b:仅当A的值为false时才计算b

Java运营商

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

如果使用||和&&形式,而不是这些操作符的|和&形式,Java将不会费心单独计算右操作数。

这是一个你是否想要缩短评估的问题——大多数时候你想这样做。

说明短路的好处的一个好方法是考虑下面的例子。

Boolean b = true;
if(b || foo.timeConsumingCall())
{
   //we entered without calling timeConsumingCall()
}

正如Jeremy和Peter提到的,短路的另一个好处是空引用检查:

if(string != null && string.isEmpty())
{
    //we check for string being null before calling isEmpty()
}

更多信息

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