Java else-if Ladder
In this page:
Basic else-if Ladder
An else-if ladder tests a sequence of conditions from top to bottom, and as soon as one evaluates to true, its block runs and every remaining condition below it is skipped entirely.
Example: Basic else-if Ladder
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) { // first true condition wins, rest skipped
System.out.println("B");
} else {
System.out.println("C");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Multiple else-if Blocks
You can chain as many else-if clauses as you need, which makes this pattern well suited to categorizing a value into one of several ranges, like assigning a letter grade based on a numeric score.
Example: Multiple else-if Blocks
public class Main {
public static void main(String[] args) {
int score = 72;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 70) {
System.out.println("C"); // categorizes into a numeric range
} else {
System.out.println("F");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Importance of Order
Since Java stops at the first true condition, ordering matters: put the most specific or narrow conditions first, because a broad condition placed too early will catch cases meant for a more specific branch below it.
Example: Importance of Order
public class Main {
public static void main(String[] args) {
int score = 95;
if (score >= 90) { // most specific/narrow condition placed first
System.out.println("A");
} else if (score >= 0) { // broad condition placed after, or it would catch everything
System.out.println("Other");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Exclusive Execution
Exactly one branch in the entire ladder ever executes per run, even if a later condition would also have evaluated true -- the ladder doesn't check anything past the first match.
Example: Exclusive Execution
public class Main {
public static void main(String[] args) {
int score = 95;
if (score >= 90) {
System.out.println("A"); // only this branch runs, even though score >= 80 is also true
} else if (score >= 80) {
System.out.println("B");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Fallback Else Block
A trailing else with no condition attached catches every value that didn't match any of the explicit checks above it, functioning as a guaranteed fallback for unexpected or unhandled input.
Example: Fallback Else Block
public class Main {
public static void main(String[] args) {
int score = -5;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("Invalid score"); // catches anything unmatched above
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: