Is there a difference between using a logical operator or a bitwise operator in an if block in Java?

前端 未结 5 2099
长发绾君心
长发绾君心 2020-12-24 10:28

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

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


        
5条回答
  •  悲&欢浪女
    2020-12-24 10:41

    The two have different uses. Although in many cases (when dealing with booleans) it may appear that they have the same effect, it is important to note that the logical-OR is short circuit, meaning that if its first argument evaluates to true, then the second argument is left unevaluated. The bitwise operator evaluates both of its arguments regardless.

    Similarly, the logical-AND is short-circuit, meaning that if its first argument evaluates to false, then the second is left unevaluated. Again, the bitwise-AND is not.

    You can see this in action here:

    int x = 0;
    int y = 1;
    System.out.println(x+y == 1 || y/x == 1);
    System.out.println(x+y == 1 |  y/x == 1);
    

    The first print statement works just fine and returns true since the first argument evaluates to true, and hence evaluation stops. The second print statement errors since it is not short circuit, and a division by zero is encountered.

提交回复
热议问题