Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- && Evaluation

Tags:

java

Can anybody help me on following issue:

I have code like:

if(cond1 && cond2 && .. && cond10)

Here, cond1 are expensive operations whose output is Boolean.

Now my question is what JAVAC will do, when cond2 output is false. Specifically, is it goes evaluate cond3 's output or stops evaluation ?

More illustratively,

if(cond1 && cond2 && .. && cond10)
  //do this

and

if(cond1){
  if(cond2){
         .
         .
         .
        if(cond10){
             //do this
                   }

are same in java (in case of execution way) ?

like image 463
Arpssss Avatar asked Apr 17 '12 16:04

Arpssss


4 Answers

The && operator always short-circuits on false. Condition 3 will only be evaluated if conditions 1 and 2 are true.

like image 135
StriplingWarrior Avatar answered Oct 31 '22 10:10

StriplingWarrior


If the entire expression is && or || then Java will use short-circuit evaluation. That means if everything is && it will stop after the first false and if everything is || it will stop after the first true.

like image 31
twain249 Avatar answered Oct 31 '22 09:10

twain249


Yes your code snippets are equivalent. The logic AND operator is in Java short-circuit.

like image 2
Martijn Courteaux Avatar answered Oct 31 '22 10:10

Martijn Courteaux


Java will exit that check as soon as it finds out that one of the values is false.

Likewise, it'll do what you expect with OR as soon as it finds out that one of the values is true.

No need to evaluate the others.

like image 2
duffymo Avatar answered Oct 31 '22 08:10

duffymo