19

Lets say I have this:

if(bool1 && bool2 && bool3) {
...
}

Now. Is Java smart enough to skip checking bool2 and bool3 if bool1 was evaluated to false? Does java even check them from left to right? I'm asking this because i was "sorting" the conditions inside my if statements by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.

MisterCal
  • 622
  • 2
  • 7
  • 22
Paul
  • 5,163
  • 3
  • 35
  • 43
  • 1
    Since you're trying to improve performance with these changes, have you tried measuring the performance before and after moving the conditions? On one hand, that should tell you whether the logic is indeed being short-circuited as explained below, and on the other, it will tell you if the magnitude of these changes are significant in the bigger picture. – Douglas Dec 20 '11 at 09:31
  • Does this answer your question? [Does Java evaluate remaining conditions after boolean result is known?](https://stackoverflow.com/questions/6352139/does-java-evaluate-remaining-conditions-after-boolean-result-is-known) – Nick is tired Oct 05 '22 at 03:24

4 Answers4

44

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

DontDivideByZero
  • 1,171
  • 15
  • 28
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
17

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
12

Please look up the difference between & and && in Java (the same applies to | and ||).

& and | are just logical operators, while && and || are conditional logical operators, which in your example means that

if(bool1 && bool2 && bool3) {

will skip bool2 and bool3 if bool1 is false, and

if(bool1 & bool2 & bool3) {

will evaluate all conditions regardless of their values.

For example, given:

boolean foo() {
    System.out.println("foo");
    return true;
}

if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
6

Yes,that is called short-circuiting.

Please take a look at this wikipedia page on short-circuiting