You can use this form to avoid creating nested blocks and make the code easier to read and understand. For example, look at the following code snippet:
if(n > 5){
System.out.println("n > 5");
} else {
if (n == 5) {
System.out.println("n == 5");
} else {
if (n == 4) {
System.out.println("n == 4");
} else {
System.out.println("n < 4");
}
}
}
}
These nested if...else statements can be replaced by if...else...if statements as follows:
if(n > 5){
System.out.println("n > 5");
} else if (n == 5) {
System.out.println("n == 5");
} else if (n == 4) {
System.out.println("n == 4");
} else {
System.out.println("n < 4");
}
Such code is easier to read and understand.
If you don't need to do anything when n < 4, you can leave out the last catch-all-the-rest-options else clause:
if(n > 5){
System.out.println("n > 5");
} else if (n == 5) {
System.out.println("n == 5");
} else if (n == 4) {
System.out.println("n == 4");
}
If you need to do something for each particular value, you can write, for example:
if(x == 5){
//do something
} else if (x == 7) {
//do something else
} else if (x == 12) {
//do something different
} else if (x = 50) {
//do something yet more different
} else {
//do something completely different
}
But there is a dedicated selection statement for such cases, called switch...case, which is easier to read and understand.