aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes || and | Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "|| and |" Watch "|| and |" New topic
Author

|| and |

sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Hi All,
see the following code and expalin me the difference etween "||" and "|"

i am not a bigneer but getting confussion.


int z = 5;
if(++z > 5 || ++z > 6) z++; // z = 7 after this code
versus:
int z = 5;
if(++z > 5 | ++z > 6) z++; // z = 8 after this code
Saurabh V Vakil
Greenhorn

Joined: Jan 30, 2008
Posts: 14
Originally posted by sumaraghavi ragha:



int z = 5;
if(++z > 5 || ++z > 6) z++; // z = 7 after this code
versus:
int z = 5;
if(++z > 5 | ++z > 6) z++; // z = 8 after this code



if(++z > 5 || ++z > 6) z++;
uses short-circuit OR(||). short-circuit OR returns true if either operand is true. since z becomes 6 after entering if, the first condition evaluates to true. since the first operand returns true, it never bothers to check the second condition. so the if() is exited after checking ++z > 6 after which z is incremented(z++). hence the value is 7.

but the second case- if(++z > 5 | ++z > 6) z++;
uses non short-circuit OR, which, always evaluates both sides of the expression. when first operand is evaluated, z becomes 6. when second operand is evaluated, z becomes 7. finally, z is again incremented to become 8.
the important thing to remember is this: while using short-circuit or(||), if the first operand in the expression evaluates to true, the second operand will never be evaluated. but when you use non short-circuit or(|), second operand will be evaluated regardless of whether the first operand returns true or false. hope this helps.
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6662
    
    5

Originally posted by sumaraghavi ragha:
Hi All,
see the following code and expalin me the difference etween "||" and "|"

i am not a bigneer but getting confussion.


int z = 5;
if(++z > 5 || ++z > 6) z++; // z = 7 after this code
versus:
int z = 5;
if(++z > 5 | ++z > 6) z++; // z = 8 after this code


Have a look at short circuit operators. The way an expression is evaluated changes based on whether the operator is shorted or not


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Thanks lot
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: || and |