在Java中的if块中使用逻辑运算符或按位运算符之间有区别吗?

在Java中的if块中使用逻辑运算符或按位运算符之间有区别吗?

问题描述:

以下两个if块的内容应该执行:

The contents of both of the following if blocks should be executed:

if( booleanFunction() || otherBooleanFunction() ) {...}
if( booleanFunction() | otherBooleanFunction() ) {...}

那么使用 | 或使用 || 之间的区别是什么?

So what's the difference between using | or using ||?

注意:我调查了这个并找到了我自己的答案,我在下面提到了答案。请随时纠正我或给自己的看法。肯定还有改进的余地!

Note: I looked into this and found my own answer, which I included below. Please feel free to correct me or give your own view. There sure is room for improvement!

逻辑运算符适用于布尔值,而位运算符适用于位。在这种情况下,效果将是相同的,但有两个不同:

The logical operator works on booleans, and the bitwise operator works on bits. In this case, the effect is going to be the same, but there are two differences:


  1. 按位运算符不适用于此,这使得它更难阅读,但最重要的是

  2. 逻辑OR运算符将评估第一个条件。如果这是真的,那么下一个条件导致什么并不重要,结果将是真的,所以第二个子句没有被执行

  1. The bitwise operator is not meant for that, which makes it harder to read but most importantly
  2. The logical OR operator will evaluate the first condition. If it's true, it does not matter what the next condition results in, the result will be true, so the second clause is not executed

这里有一些方便的代码来证明这一点:

Here's some handy code to prove this:

public class OperatorTest {

    public static void main(String[] args){
        System.out.println("Logical Operator:");
        if(sayAndReturn(true, "first") || sayAndReturn(true, "second")){
            //doNothing
        }

        System.out.println("Bitwise Operator:");
        if(sayAndReturn(true, "first") | sayAndReturn(true, "second")){
            //doNothing
        }
    }

    public static boolean sayAndReturn(boolean ret, String msg){
        System.out.println(msg);
        return ret;
    }
}