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

Miquel picture Miquel · Jun 22, 2012 · Viewed 28k times · Source

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!

Answer

arshajii picture arshajii · Jun 22, 2012

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.