Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Lets say I have this:

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

Now. Is Java smart enough to skip checking bool2 and bool2 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's 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.

like image 886
Paul Avatar asked Dec 20 '11 08:12

Paul


People also ask

How do you do multiple conditions with single if statements?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

Can you have 3 conditions in an if statement?

If you have to write an IF statement with 3 outcomes, then you only need to use one nested IF function. The first IF statement will handle the first outcome, while the second one will return the second and the third possible outcomes. Note: If you have Office 365 installed, then you can also use the new IFS function.

How many conditions can be in an if statement Java?

Technically only 1 condition is evaluated inside an if , what is ascually happening is 1 condition gets evaluated and its result is evaluated with the next and so on...


1 Answers

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.

like image 194
Tomasz Nurkiewicz Avatar answered Oct 10 '22 13:10

Tomasz Nurkiewicz