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

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

其他回答

来看看:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

|是位包含或

||为逻辑或

| is the binary or operator

|| is the logic or operator

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

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

仔细阅读本主题后,我仍然不清楚使用|作为逻辑运算符是否符合Java模式实践。

我最近修改了一个pull请求中的代码

if(function1() | function2()){
  ...
}

必须改为

boolean isChanged = function1();
isChanged |= function2();
if (isChanged){
  ...
}

实际接受的版本是什么?

Java文档没有提到|是逻辑上非短路的OR运算符。

对投票不感兴趣,更感兴趣的是找出标准?! 两个代码版本都按照预期进行编译和工作。

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

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

混合的时候要小心。