APrep Open the app

AP Computer Science A · Unit 2: Selection & Iteration

2.4 Else If Statements

Chaining conditions with else if

An else if statement lets you test multiple conditions in sequence after an initial if. Java checks each condition top to bottom and executes the first block whose condition is true, then skips the rest of the chain. This avoids nested if statements and makes multi-way branching cleaner and more readable.

Order matters

Since only the first true condition runs, the order of conditions affects results. If ranges overlap, a more specific condition should usually be checked before a more general one, or it will never be reached. Placing a broad condition first can accidentally shadow later, more specific conditions.

Optional final else

A final else (with no condition) acts as a catch-all, running only if none of the previous if/else if conditions were true. It's optional — you can have an if/else if chain without one — but it's useful for handling default or unexpected cases.

Key terms

else if statement
Tests an additional condition after a preceding if is false; allows multiple exclusive branches.
Order of evaluation in a chain
Conditions are checked top to bottom; only the first true condition's block executes.
Final else (no condition)
A catch-all block that runs only if all previous conditions in the chain were false; optional.
Shadowing in else if chains
When a broader condition is placed before a specific one, preventing the specific condition from ever being reached.
Mutual exclusivity of if/else if branches
Only one block in the chain executes per run, even if multiple conditions would be true independently.

Try an AP-style question

Code

int score = 85;
String g;
if (score >= 90) g = "A";
else if (score >= 80) g = "B";
else if (score >= 70) g = "C";
else g = "F";

What is g?

  1. "A"
  2. "B"
  3. "C"
  4. "F"
Show the answer

B. First true condition wins.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 2.4 free in APrep