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

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

通常在有前加和后加运算符时使用。请看下面的代码:

package ocjpPractice;
/**
 * @author tithik
 *
 */
public class Ex1 {

    public static void main(String[] args) {
    int i=10;
    int j=9;
    int x=10;
    int y=9;
    if(i==10 | ++i>j){
        System.out.println("it will print in first if");  
        System.out.println("i is: "+i);
    }

    if(x==10 ||++x>y){
        System.out.println("it will print in second if");   
        System.out.println("x is: "+x);
    }
    }
}

输出:

它将首先打印 I是:11 它将以秒if打印 X = 10

两个if块相同,但结果不同。 当存在|时,两个条件都将被计算。但如果它是||,它将不会评估第二个条件,因为第一个条件已经为真。

| is the binary or operator

|| is the logic or operator

||是逻辑或运算符,|是位或运算符。

boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;

来看看:

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

|是位包含或

||为逻辑或