Reference Guide

Key Ideas

  • A nested if is an if inside the body of another if or else. The inner condition is checked only when the outer path is taken.
  • An else if chain (multi way selection) tests conditions top to bottom. The first true condition wins and every remaining branch is skipped.
  • Order matters. Put the most specific or strictest condition first.
  • A final else is optional. It catches everything the earlier conditions did not.
  • Use nesting when the second question only makes sense after the first one is answered.

Two Shapes

else if chain nested if
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C or below";
}
if (isRaining) {
  if (isWindy) {
    msg = "Wear a raincoat";
  } else {
    msg = "Bring an umbrella";
  }
} else {
  msg = "Enjoy the sun";
}
One question with many possible answers A second question asked only in one branch

College Board Requirements

AP CSA Unit 2, Topic 2.4: Nested if Statements.

This lesson is built directly against the College Board’s stated learning objective for this topic:

Represent branching logical processes by using nested selection statements.

Topic 2.4, Nested if Statements, is required content on the AP Computer Science A Exam. The learning objective quoted above is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.


Lesson Plan

Learning Objective: Represent branching logical processes by using nested selection statements.

Success Criteria: You can build an else if chain that handles three or more cases, explain why only the first true branch runs, and order the conditions so no case is unreachable.

Tech Talk & Introduction

An else if chain tests conditions in order and stops at the first one that is true. A nested if puts a second decision inside a branch that has already been taken.

  • Only one branch of a chain ever runs, even if several conditions would be true.
  • Order matters. A broad condition placed first makes the narrower ones below it unreachable.
  • Nesting is for decisions that only make sense after an earlier decision was true.

Code Examples

A. Simple: else if in Code

Run it, then change myAge to 19, 15, 13 and predict the output each time.

Code Runner Challenge

else if chain: only the first true branch runs. Change myAge and run again.

View IPYNB Source
// CODE_RUNNER: else if chain: only the first true branch runs. Change myAge and run again.
public class AgeChecker {
    public static void main(String[] args) {
        int myAge = 17;   // try 19, 15, and 13
        System.out.println("Current age: " + myAge);

        if (myAge >= 18) {
            System.out.println("You can register to vote.");
            System.out.println("You are old enough for a license.");
        } else if (myAge >= 16) {
            System.out.println("You are old enough for a license.");
        } else if (myAge >= 15) {
            System.out.println("You can get a learner's permit.");
        } else {
            System.out.println("A few more years to go.");
        }
    }
}
AgeChecker.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Activity 1: Grade Machine

Slide the score. Only the first true condition runs, and everything after it is skipped, even if it would also be true.

else if Chain
Notice that a score of 95 is also >= 80, but the B branch never runs.

Activity 2: Order Matters

Order Matters
Both questions use the same idea: the first true condition wins.
Question 1

What does this print when score is 95?

if (score >= 60) {
System.out.println("D");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 90) {
System.out.println("A");
}
Question 2

These are separate if statements, not a chain. What prints when score is 95?

if (score >= 90) {
System.out.println("A");
}
if (score >= 80) {
System.out.println("B");
}
if (score >= 70) {
System.out.println("C");
}

Activity 3: Trace a Nested if

Step through the weather program. Change the two settings and watch which questions Java even bothers to ask.

Weather Advice
The inner question about wind is only asked when it is raining.

Activity 4: Assemble the Chain

Build a ticket price program: children under 5 are free, students under 18 pay $8, everyone else pays $12.

Ticket Prices
Get the order of the conditions right or the wrong people pay.
int age = 15;
int price;
if (age < 5) {
price = 0;
} else if (age < 18) {
price = 8;
} else {
price = 12;
}
System.out.println("Price: $" + price);

Popcorn Hack

Add branches so the program prints the right letter for every average: A (90 and up), B (80 to 89), C (70 to 79), D (60 to 69), F (below 60). Test with 90, 75, 61, and 40.

Code Runner Challenge

Popcorn hack: extend the chain with C, D, and F.

View IPYNB Source
// CODE_RUNNER: Popcorn hack: extend the chain with C, D, and F.
public class GradeEvaluator {
    public static void main(String[] args) {
        double myAverage = 75;   // test with 90, 75, 61, 40
        System.out.println("Current average: " + myAverage);

        if (myAverage >= 90) {
            System.out.println("You have an A average.");
        } else if (myAverage >= 80) {
            System.out.println("You have a B average.");
        }
        // TODO: add C, D, and F branches
    }
}
GradeEvaluator.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack

Two short tasks.

  1. Finish the runner below with a nested if: members get a discount, and members who spend $100 or more get a bigger one.
  2. Answer the quick check.

Code Runner Challenge

Homework: nested if for member discounts. Expected for a member spending 120.0: Discount 20.0% and You pay $96.0.

View IPYNB Source
// CODE_RUNNER: Homework: nested if for member discounts. Expected for a member spending 120.0: Discount 20.0% and You pay $96.0.
public class Discount {
    public static void main(String[] args) {
        boolean isMember = true;   // test all four combinations
        double total = 120.0;
        double discount = 0;

        // TODO: if isMember is true:
        //          if total >= 100, discount = 0.20
        //          otherwise discount = 0.10
        //       if isMember is false, discount stays 0

        System.out.println("Discount: " + (discount * 100) + "%");
        System.out.println("You pay: $" + (total - total * discount));
    }
}
Discount.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Homework Quick Check
One question.

What does this print when temp is 75? Type the exact word.

if (temp > 85) {
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");
}

References

College Board Course and Exam Description

Topic 2.4, Nested if Statements, is required content on the AP Computer Science A Exam. The learning objective quoted in section 3 (College Board Requirements) is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.

Outside Academic Reference

A nested selection is simply an if statement appearing as the statement inside another branch; the specification does not define a separate construct for it, which is why the ordinary rules about braces and scope apply unchanged.

Reference List

College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a

Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.9

All Java lessons