Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# || and |

sumaraghavi ragha
Ranch Hand
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
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
Posts: 6663
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

sumaraghavi ragha
Ranch Hand
Posts: 118
Thanks lot

 It is sorta covered in the JavaRanch Style Guide.