Noufal
Noufal

Reputation: 447

Why Logical operators, when there is Bitwise operators in java

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.

Upvotes: 2

Views: 1588

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

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:

Upvotes: 1

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

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    

Upvotes: 7

rocketboy
rocketboy

Reputation: 9741

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.

Upvotes: 2

Related Questions