在Java中的if块中使用逻辑运算符或按位运算符之间有区别吗? [英] Is there a difference between using a logical operator or a bitwise operator in an if block in Java?

查看:202
本文介绍了在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;
    }
}

这篇关于在Java中的if块中使用逻辑运算符或按位运算符之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆