Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 902
Miquel Avatar asked Jun 22 '12 12:06

Miquel


2 Answers

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.

like image 146
arshajii Avatar answered Oct 05 '22 06:10

arshajii


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. 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;
    }
}
like image 29
Miquel Avatar answered Oct 05 '22 08:10

Miquel