Skip to content
Advertisement

How does Java deal with multiple conditions inside a single IF statement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement