March 02, 2010

What is difference between | and || (logical operators) in java ?

if | is applied between two variable like a=4 and b=2
then a|b gives 4==> 0100 in binary
2==> 0010 in binary
______
6==> 0110 in binary.
if a||b it returns true if either a is non zero or b is nonzero or both are nonzeros
so 4||2 returns ==>true.

(or)


|| is the logical or operator while | is the bitwise or operator.

boolean a = true;
boolean b = false;

if (a || b) {
}

int a = 0x0001;
a = a | 0x0002;

In Addition to the fact that | is a bitwise-operator: || is a short-circuit operator - when one element is false, it will not check the others.

if(something || someotherthing)
if(something | someotherthing)

if something is TRUE, || will not evaluate someotherthing, while | will do. If the variables in your if-statements are actually function calls, using || is possibly saving a lot of performance.

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts