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

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


当前回答

非短路是有用的。有时你想确保两个表达式都有值。例如,假设您有一个从两个单独的列表中删除对象的方法。你可能想这样做:

class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

如果您的方法改为使用条件操作数,如果第一个列表返回false,则它将无法从第二个列表中删除对象。

//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

它并不是特别有用,并且(与大多数编程任务一样)您可以通过其他方法实现它。但这是位操作数的一个用例。

其他回答

因此,在其他答案的基础上,举个例子,短路在以下防御性检查中至关重要:

if (foo == null || foo.isClosed()) {
    return;
}

if (bar != null && bar.isBlue()) {
    foo.doSomething();
}

使用|和&可能导致在这里抛出NullPointerException。

| is the binary or operator

|| is the logic or operator

一个主要的区别是||和&&表现出“短路”,所以RHS只在需要时进行评估。

如。

if (a || b) {
    path1...
} else {
    path2..
}

如果a为真,则不会测试b,并执行path1。如果使用|,则即使'a'为真,两边也将被求值。

看这里和这里,了解更多信息。

希望这能有所帮助。

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

例如:

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
...

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