Lesson 2.4: Nested if Statements

Unit 2 · Lesson 2.4 · Code Mechanics

Lesson 2.4: Nested if Statements

🕑 20–25 min·8 Practice Questions·4 Mastery Questions·Output Predictor + Bug Hunt

Key Vocabulary

Term Definition
nested if A selection statement placed inside the body of another selection statement. The inner condition is only evaluated when the outer condition is true. (EK 2.4.A.1)
multiway selection An if-else-if chain that evaluates conditions in order and executes at most one branch — the first one whose condition is true. (EK 2.4.A.3)
outer condition The boolean expression of the enclosing if. Controls whether any inner statement is reached at all.
inner condition The boolean expression of the nested if. Only evaluated when the outer condition is true. (EK 2.4.A.2)
trailing else An else at the end of an if-else-if chain that executes when no preceding condition is true. Acts as a default case.
dangling else Ambiguity in which if an else belongs to when braces are omitted. Java always pairs an else with the nearest unmatched if above it.

Nested if Statements (EK 2.4.A.1 & 2.4.A.2)

A nested if is any selection statement that appears inside the body of another selection statement. Nesting lets you express conditions that only make sense to check after a prerequisite condition has passed. The critical rule from the CED: the boolean expression of the inner nested if is evaluated only if the boolean expression of the outer if evaluates to true.

This has a practical consequence: if the outer condition is false, the inner if is never reached at all, and any side effects inside the inner block do not occur. AP exam trace questions often exploit this by giving you an input where the outer condition is false and asking what happens — the answer is the inner block is completely skipped.

Nested if Structure

if (outerCondition) {
    // outer body: runs when outerCondition is true
    if (innerCondition) {
        // inner body: runs when BOTH conditions true
    } else {
        // inner else: runs when outer true, inner false
    }
} else {
    // outer else: runs when outerCondition is false
    // innerCondition is NEVER evaluated here
}

Worked Example — Full Trace with Three Inputs

int score = 85;
if (score >= 60) {               // outer: 85 >= 60 = true
    if (score >= 90) {           // inner: 85 >= 90 = false
        System.out.println("A"); // SKIPPED
    } else {
        System.out.println("B"); // runs: outer true, inner false
    }
} else {
    System.out.println("F");     // SKIPPED: outer was true
}

score=85 → outer true, inner false → prints B.
score=95 → outer true, inner true → prints A.
score=40 → outer false → inner never evaluated → prints F.

Nested vs. separate if statements

A nested if inside an outer if body is fundamentally different from two separate if statements. With separate statements both conditions are always evaluated. With nesting, the inner condition is skipped when the outer is false. Use nesting when the inner question only makes logical sense after the outer condition passes.

Worked Example — Nested vs. Separate

// Nested: inner only runs when outer is true
if (isLoggedIn) {
    if (isAdmin) {
        System.out.println("Admin panel");
    }
}

// Separate: BOTH always checked, even when not logged in
if (isLoggedIn) { /* ... */ }
if (isAdmin) {                  // checked even when not logged in
    System.out.println("Admin panel");  // security flaw!
}

Nesting enforces the logical dependency: admin panel should only be reachable when logged in. Two separate if statements break this dependency.

Multiway Selection: if-else-if (EK 2.4.A.3)

An if-else-if chain is a multiway selection that evaluates conditions in order from top to bottom. The moment a condition evaluates to true, its body executes and the rest of the chain is skipped entirely. At most one branch executes, regardless of how many conditions are true. If a trailing else is present, it executes only when all preceding conditions were false.

Multiway Selection Syntax

if (conditionA) {
    // executes when A is true (stops here)
} else if (conditionB) {
    // executes when A is false AND B is true (stops here)
} else if (conditionC) {
    // executes when A and B are false AND C is true
} else {
    // executes when ALL preceding conditions are false
    // (trailing else — optional but common)
}

Worked Example — Grade Assignment (score = 85)

int score = 85;
String grade;
if (score >= 90) {
    grade = "A";                 // 85 >= 90 = false, skip
} else if (score >= 80) {
    grade = "B";                 // 85 >= 80 = true → runs, DONE
} else if (score >= 70) {
    grade = "C";                 // never reached
} else {
    grade = "D or F";            // never reached
}
System.out.println(grade);       // B

Even though score >= 70 and score >= 80 are both true for 85, only the first matching branch executes. This is the defining characteristic of multiway selection.

if-else-if vs. separate if statements

Property if-else-if chain
Branches that execute At most 1 (the first true condition).
Separate if blocks: all true conditions execute.
Condition evaluation order Top to bottom; stops at first true.
Separate if blocks: all conditions always evaluated.
When to use Mutually exclusive categories (grade bands, speed zones, tax brackets).
Separate if blocks: independent checks that can each be true.

AP Trap: Order of Conditions in if-else-if

Always check the most specific (narrowest) condition first. If you check score >= 60 before score >= 90, a score of 95 matches the first branch and gets grade "D" — the "A" branch is unreachable. Correct order: 90, then 80, then 70, then 60, then else. Most specific first, least specific last.

AP Trap: Dangling else in Nested Structures

Without braces, each else pairs with the nearest unmatched if. In deeply nested code this can silently produce the wrong pairing. Always use braces in nested structures. The AP exam deliberately tests brace-free nested code to see if you know which if each else belongs to.

AP Trap: Inner Condition Evaluated When Outer Is False

Students sometimes think "both conditions are checked independently." This is wrong for nested if statements. If the outer condition is false, the inner condition is never evaluated. This matters when the inner condition has a side effect (like a method call) — it does not execute when the outer is false. (EK 2.4.A.2)

Real-World Connection

Nested selection is everywhere. A bank ATM first checks if your card is valid (outer), then checks if your PIN is correct (inner) — the PIN check only happens if the card check passes. A streaming service first checks if you have an active subscription (outer), then checks if the content is in your region (inner). Tax bracket calculations use multiway if-else-if chains to assign exactly one rate based on income range. Every tiered system — shipping rates, hotel pricing, game difficulty levels — is a multiway selection in code.

Summary

  • Nested if: a selection statement inside another selection statement. (EK 2.4.A.1)
  • Inner condition is only evaluated when the outer condition is true. (EK 2.4.A.2)
  • Multiway selection (if-else-if): evaluates conditions in order; at most one branch executes. (EK 2.4.A.3)
  • Trailing else: catches the case when no condition in the chain is true.
  • Order matters: most specific condition first in an if-else-if chain.
  • Dangling else: always use braces in nested structures to make pairing explicit.
  • Nested vs. separate: use nesting when the inner question only makes sense after the outer passes; use separate ifs when both are independent.

Nested if Statements

A nested if is a selection statement placed inside the body of another selection statement. The inner condition is only evaluated when the outer condition is true.

Nested if Structure

if (outerCondition) {
    if (innerCondition) {
        // both conditions true
    } else {
        // outer true, inner false
    }
}

Example: Grade with Pass/Fail Gate

int score = 85;
if (score >= 60) {
    if (score >= 90) {
        System.out.println("Excellent pass");
    } else {
        System.out.println("Standard pass");
    }
} else {
    System.out.println("Fail");
}

Output: Standard pass. The inner check only runs because 85 ≥ 60.

Multiway Selection: if-else-if

An if-else-if chain evaluates conditions in order. Only the first true branch executes. A trailing else runs when no condition is true.

if-else-if Syntax

if (conditionA) {
    // A true
} else if (conditionB) {
    // A false, B true
} else if (conditionC) {
    // A and B false, C true
} else {
    // none true
}

AP Trap: Order of Conditions Matters

Always check the most specific condition first. If score >= 60 is checked before score >= 90, a score of 95 matches the first branch and the A grade is unreachable.

AP Trap: Dangling else

Without braces, an else pairs with the nearest unmatched if. Always use braces in nested structures to make pairing explicit.

Tier 2 · AP Practice

Practice Questions

MCQ 1
What is printed when x = 4?

if (x > 0) {
    if (x > 5) {
        System.out.println("High");
    } else {
        System.out.println("Low");
    }
}
A High
B Low
C Nothing is printed
D High then Low
4 > 0 true (enter outer). 4 > 5 false (inner else). Prints: Low.
MCQ 2
What is printed when x = -1?

if (x > 0) {
    if (x > 5) {
        System.out.println("High");
    } else {
        System.out.println("Low");
    }
}
A High
B Low
C Nothing is printed
D Compile error
-1 > 0 is false. Outer if is false so entire block is skipped. The inner condition is never evaluated.
MCQ 3
What is printed when score = 95?

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}
A A
B A then B
C B
D A then B then C
95 ≥ 90 is true. A prints. All remaining branches are skipped — in multiway selection only the first true branch executes.
MCQ 4
Which is NOT true about a multiway if-else-if selection?
Predict the answer before reading options.
A At most one branch executes
B Conditions are evaluated in order from top to bottom
C If no condition is true and there is a trailing else, the else runs
D All conditions are evaluated regardless of which one is true first
D is false. Once the first true condition is found, remaining conditions are NOT evaluated. A, B, and C are all true.
MCQ 5
What is printed when score = 60?

if (score >= 60) {
    System.out.println("Pass");
} else if (score >= 90) {
    System.out.println("Excellent");
} else {
    System.out.println("Fail");
}
A Excellent
B Fail
C Pass
D Pass then Excellent
60 ≥ 60 is true so Pass prints immediately. The Excellent branch is unreachable — a logic error since ≥60 is checked before ≥90.
MCQ 6
What is printed when temp = 72?

if (temp >= 90) {
    System.out.println("Hot");
} else if (temp >= 70) {
    System.out.println("Warm");
} else if (temp >= 50) {
    System.out.println("Cool");
} else {
    System.out.println("Cold");
}
A Warm
B Cool
C Warm then Cool
D Hot
72 ≥ 90? No. 72 ≥ 70? Yes. Warm prints. Remaining branches skipped.
MCQ 7
What is printed when x = 6?

if (x > 5)
    if (x > 8)
        System.out.println("Very high");
else
    System.out.println("Low");
Which if does the else belong to?
A Very high
B Nothing is printed
C Very high then Low
D Low
The else pairs with the nearest unmatched if — if (x > 8). x=6 > 5 true (enter outer). x=6 > 8 false (its else runs). Prints: Low.
MCQ 8
What is the correct order for a grade-assigning if-else-if chain (A=90+, B=80+, C=70+, F otherwise)?
A Check ≥70 first, then ≥80, then ≥90, then F
B Check ≥90 first, then ≥80, then ≥70, then F
C Any order works since conditions are mutually exclusive
D Check F first, then ≥70, then ≥80, then ≥90
B. Must check most specific (highest threshold) first. If ≥70 is checked first, a 95 matches it and prints C. The conditions are NOT mutually exclusive — 95 satisfies all three.
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor — Nested if Statements
Trace through nested conditions. What executes?
Question 1 of 6Score: 0

🎉 Done!
You got 0 of 6 correct.
Bug Hunt — Nested if Statements
Each snippet has one bug (or no bug). Click the buggy line, then submit.
Bug 1 of 7Caught: 0

🎉 Done!
You got 0 of 7 correct.
Tier 3 · AP Mastery

Mastery: Nested if Analysis

What is printed when x = 3 and y = 7?

if (x > 2) {
    if (y > 5) {
        System.out.println("Both");
    } else {
        System.out.println("X only");
    }
} else {
    System.out.println("Neither");
}
Predict the answer before reading options.
A X only
B Neither
C Both
D Both then X only
x=3 > 2 true (enter outer). y=7 > 5 true (enter inner). Prints: Both.
A student categorizes age: child (<13), teen (13–17), adult (18+). Which chain is correct?
Predict the answer before reading options.
A
if (age < 13) {
    System.out.println("Child");
} else if (age < 18) {
    System.out.println("Teen");
} else {
    System.out.println("Adult");
}
B
if (age >= 18) {
    System.out.println("Adult");
} if (age >= 13) {
    System.out.println("Teen");
} if (age < 13) {
    System.out.println("Child");
}
C
if (age < 18) {
    System.out.println("Teen");
} else if (age < 13) {
    System.out.println("Child");
} else {
    System.out.println("Adult");
}
D
if (age < 13) {
    System.out.println("Child");
} if (age < 18) {
    System.out.println("Teen");
} else {
    System.out.println("Adult");
}
A is correct. B uses three independent ifs — an 18-year-old prints Adult then Teen. C checks <18 before <13 so children print Teen. D uses two separate ifs so a child prints Child then Teen. Only A uses a proper else-if chain in the right order.
What is printed when n = 15?

if (n % 3 == 0) {
    if (n % 5 == 0) {
        System.out.println("FizzBuzz");
    } else {
        System.out.println("Fizz");
    }
} else if (n % 5 == 0) {
    System.out.println("Buzz");
} else {
    System.out.println("" + n);
}
Check both divisibility conditions for n=15.
A Fizz
B Buzz
C 15
D FizzBuzz
15 % 3 = 0 (true, enter outer). 15 % 5 = 0 (true, enter inner). Prints: FizzBuzz.
How many branches can execute for a single input in a 4-condition if-else-if-else chain?
Predict the answer before reading options.
A Up to 4, one per condition
B Exactly 1
C 0 or 1
D At most 2
B. With a trailing else, exactly 1 branch always executes — either the first true condition or the else. C would be correct for a chain without an else.
Extension

FizzBuzz — A Classic Algorithm

The FizzBuzz problem: for numbers 1–20, print Fizz if divisible by 3, Buzz if divisible by 5, FizzBuzz if divisible by both, and the number otherwise. What happens if you check divisibility by 3 or 5 before checking divisibility by both? Try restructuring the conditions and trace what changes.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]