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

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


当前回答

当我遇到这个问题时,我创建了测试代码来了解这个问题。

public class HelloWorld{

   public static boolean bool(){
      System.out.println("Bool");
      return true;
   }

   public static void main(String []args){

     boolean a = true;
     boolean b = false;

     if(a||bool())
     {
        System.out.println("If condition executed"); 
     }
     else{
         System.out.println("Else condition executed");
     }

 }
}

在这种情况下,我们只改变if条件的左边值加上a或b。

||场景,当左侧为true时[if(a||bool())]

输出"If条件已执行"

||场景,当左边为false [if(b||bool())]

输出-

Bool
If condition executed

||结论当使用||时,右侧只检查左侧为假。

|场景,当左侧为true时[if(a|bool())]

输出-

Bool
If condition executed

|场景,当左侧为false [if(b|bool())]

输出-

Bool
If condition executed

|结论使用|时,请同时检查左右两侧。

其他回答

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

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;
    }
}

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

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

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

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

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

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

如。

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

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

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

希望这能有所帮助。