-1

Please I am trying to find the difference between the two. Below is example

for multiple && operator:

if(a>b && b>c){
    // do some thing
}

for nested if condition

if(a>b){
    if(b>c){
        //do some thing`enter code here`
    }
}

Which is fast and which should be use. What is the difference between two. I want to know the performance to when complexity increase.

domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
vyas
  • 414
  • 3
  • 8
  • @JRowan see [Oracle.com](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) If you combine multiple _&&_ the second will only be evaluated if the first is true, the third if the second is true and so on... – ifloop Apr 07 '14 at 07:09

6 Answers6

0

There is only a minor performance difference and opting multiple && operator make the code simple and easy to understand

aΨVaN
  • 1,104
  • 2
  • 9
  • 18
0

These two are equivalent:

if (condition1) block1 
else if (condition2) block2

if (condition1) block1 
else
{
   if (condition2) block2
}

I presume they also compile to the same assembly, so there should be no difference.

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
0

The differences are mainly in readability and maintenance.

Concatenation of 2 logical conditions should usually imply that there is a semantic relation between them.

Another thing to consider is the scoping. The nested if gives you additional flexibility in this area.

Harshal Benake
  • 2,391
  • 1
  • 23
  • 40
0

They will actually both be the same. Either way, you have to test at least one condition. In both examples, if a was less than b, the evaluation would end and the program would proceed to the next bit of code. Also, modern java compilers will actually compile both of these examples into the same bytecode. So, to answer your question, either is fine, and one will not show better performance than the other. I personally use the first example because it is more compact and I feel it is easier to read.

ArmaAK
  • 587
  • 6
  • 21
0

I think 1st one is the standard method.

 if(a>b && b>c)
{
// do some thing
}

it reduces the number of lines. that means it follows don't repeat yourself (DRY) principle.In java the execution is line by line.

Sanu
  • 455
  • 1
  • 6
  • 17
0

Note that ANSI C does not require a particular order of operations in the case of the logical AND version (&&). This means the two may yield different results if the second test depends on the outcome of the first.

It is also wise to surround each test in extra brackets to avoid operator precedence issues.

ntremble
  • 71
  • 4