我只是想知道为什么我们通常在两个布尔值之间使用逻辑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将不会费心单独计算右操作数。

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

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

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()
}

更多信息

其他回答

1).(expression1 | expression2), |运算符将计算expression2,而不管expression1的结果是真还是假。

例子:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b | test());
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}

2).(expression1 || expression2),如果expression1为真,||操作符将不计算expression2。

例子:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b || test())
        {
            System.out.println("short circuit!");
        }
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}
| 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
...

操作符||和&&被称为条件操作符,而|和&被称为位操作符。它们有不同的用途。

条件操作符仅适用于在左侧和右侧都静态求值为布尔值的表达式。

位操作符适用于任何数字操作数。

如果希望执行逻辑比较,则应该使用条件操作符,因为您将向代码添加某种类型安全。

||通过OR'ing两个值返回布尔值(这就是为什么它被称为逻辑或)

IE:

if (A || B) 

如果A或B中有一个为真则返回真,如果它们都为假则返回假。

|是一个对两个值执行位操作的运算符。为了更好地理解位操作,你可以阅读这里:

http://en.wikipedia.org/wiki/Bitwise_operation