2
votes

I know that the Bitwise operators &, | and ^ are EITHER bitwise operators OR logical operators ... depending on the types of the operands.

If the operands are integers, the operators are bitwise. If they are booleans, then the operators are logical.

Then why there are Logical operators &&,|| and! ? I believe there will be some situations where we can use only logical operator, and so they are.

So, can anyone explain such a situation? Or any advantage over bitwise ops.

3
One reason they are both in Java is because they were both in C.Andy Thomas

3 Answers

7
votes

Operators && and || evaluates lazily. This means that only one side might be evaluated.

Operators & and | evaluates eagerly, this means that always both sides are evaluated.

It is very important when you expressions have side effects.

Examples

x = 0;
(x++ == 0) || (x++ == 1); // x is 1    

x = 0;
(x++ == 0) | (x++ == 1); // x is 2    
2
votes

Logical operators &&,|| etc let you short circuit the logic.

1==1 || complexMethod(/*param*/)

complexMethod() will not execute.

1==1 | complexMethod(/*param*/)

complexMethod() will execute.

Short circuiting basically means the condition will be evaluated only up to where it is necessary and not beyond that.

1
votes

Uses in Short-circuit evaluation like

Ex:

see &&

if(Condition1 && condition2){

}

and ||

 if(Condition1 || condition2){

}

in these cases

in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression: