• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Logical Operators

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello,

I saw an example in the K/B book, about logical operators:

int y = 5;
int x = 2;
if ((x > 3) && (y < 2) | doStuff()) { // OR is a Not Short-Circuit operator
System.out.println("true");
}

The code does not print anything, because there is used the "&&" operator (short-circuit operator), that doesn't check the second operand if the first is false. In this example, (x>3) is false, so it doesn't check anymore what is after "&&".

This is ok, I understand, but my dilema is that if I change a little bit the code (the OR operator is no longer Not Short-Circuit, but is a Short-Circuit), the output is "true".

int y = 5;
int x = 2;
if ((x > 3) && (y < 2) || doStuff()) { // OR operand is Short-Circuit
System.out.println("true");
}

Can anyone tell me why the second operator changes the result ?

Thank you
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out the precedence of | and && and ||.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int y = 5;
int x = 2;
if ((x > 3) && (y < 2) || doStuff()) {
System.out.println("true");
}

here, as there is || operator used, the expression becomes
((x > 3) && (y < 2))|| doStuff()
and || operator will check the RHS if the LHS is false which is the case here
Note that y<2 is not evaluated
also Note that true||false&&false will result true and RHS of || will not be evaluated this is because the expression is evaluated as
true||(false&&false) and if LHS is true RHS wont be evaluated.
 
reply
    Bookmark Topic Watch Topic
  • New Topic