Haych Haych - 5 months ago 10
Java Question

If Else VS Multiple If Statements

I always use multiple if statements when coding:

if(logicalCheck){
...
}

if(secondLogicalCheck){
...
}


and rarely use If Else. I understand that using my way means that more than one of my logical checks can be fulfilled and only one in an if else chain can occur.

My question is, is there any performance benefits in using one method over the other in C, Java or JavaScript? Is there anything particular wrong with using multiple if statements?

Answer

Using only if, interpreter or whatever will test all conditions but if you use else if (if possible) then on passing any condition , next else if will not be tested or checked.

if (age < 10){
   // do something
}
if (age < 20 && age > 10){
   // do something
}
if (age < 30 && age > 20){
   // do something
}

All conditions will be tested/compared

but in this scenario

if (age < 10){
   // do something
}
else if (age < 20 && age > 10){
   // do something
}
else if (age < 30 && age > 20){
   // do something
}

if age is 5, only first condition will be tested.