← Back to Core Java Course | Chapter 4: Control Flow | Lesson 3 of 9

Java else-if Ladder

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

java
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");
		}
	}
}

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

java
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");
		}
	}
}

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

java
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");
		}
	}
}

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

java
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");
		}
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.