This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!
See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Logical Operators  RSS feed

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Check out the precedence of | and && and ||.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!