Difference Between If and Else If?
The difference is that if the first if
is true, all of the other else if
s won't be executed, even if they do evaluate to true. If they were individual if
s, nevertheless, all of the if
s will be executed if they evaluate to true.
If you have used multiple if
statements then if the condition is true
all will be executed. If you have used if
and else if
combination only one will be executed where first comes the true value
// if condition true then all will be executed
if(condition) {
System.out.println("First if executed");
}
if(condition) {
System.out.println("Second if executed");
}
if(condition) {
System.out.println("Third if executed");
}
// only one will be executed
if(condition) {
System.out.println("First if else executed");
}
else if(condition) {
System.out.println("Second if else executed");
}
else if(condition) {
System.out.println("Third if else executed");
}
if(i == 0) ... //if i = 0 this will work and skip the following else-if statements
else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip the following else-if statement
else if(i == 2) ...// if i not equal to 0 or 1 and if i = 2 the statement will execute
if(i == 0) ...//if i = 0 this will work and check the following conditions also
if(i == 1) ...//regardless of the i == 0 check, this if condition is checked
if(i == 2) ...//regardless of the i == 0 and i == 1 check, this if condition is checked
For the first case: once an else if (or the first if) succeeds, none of the remaining else ifs or elses will be tested. However in the second case every if will be tested even if all of them (or one of them) succeeds.