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

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

| is the binary or operator

|| is the logic or operator

有很多用例表明为什么你应该选择||而不是|。有些用例必须使用|操作符来检查所有条件。

例如,如果您希望检查表单验证,并且希望向用户显示所有带有错误文本的无效字段,而不仅仅是第一个无效字段。

||算子是,

   if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

   private boolean checkIfEmpty(Widget field) {
      if(field.isEmpty()) {
        field.setErrorMessage("Should not be empty!");
        return true;
      }
      return false;
   }

因此,在上面的代码片段中,如果用户提交的表单中所有字段都是空的,那么只有nameField将显示错误消息。但是,如果你把它改成,

   if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

无论真实情况如何,它都会在每个字段上显示正确的错误信息。

| =位或,|| =逻辑或

附注:Java有|=,但没有||=

必须使用||的一个例子是,当第一个表达式是测试第二个表达式是否会爆炸时。例:在以下情况下使用单个|可能导致NPE。

public static boolean isNotSet(String text) {
   return text == null || text.length() == 0;
}