Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Logical Operators  RSS feed

 
camelia codarcea
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
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the precedence of | and && and ||.
 
shyam kumarK
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!