ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.4

Nested if Statements

Skill 2.ASkill 4.A

Big idea: Nesting puts one decision inside another. An if-else-if chain checks conditions in order and runs only the first one that's true.

Learning objectives
  • Develop code to represent nested branching logical processes and determine the result of these processes.

Multiway selection with if-else-if

Conditions are tested from the top. As soon as one is true, its block runs and the rest of the chain is skipped. The final else catches everything else. Because of this, put the most restrictive condition first.

Code
int score = 85;
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");
}
Output
B

Chain vs. separate ifs

Separate if statements are all checked, so several can run. A chain runs at most one.

Code
int n = 95;
if (n >= 90) System.out.print("A");
if (n >= 80) System.out.print("B");
if (n >= 70) System.out.print("C");
System.out.println();
if (n >= 90) System.out.print("A");
else if (n >= 80) System.out.print("B");
else if (n >= 70) System.out.print("C");
System.out.println();
Output
ABC
A

Nested decisions and the dangling else

An inner if is only checked when the outer condition is true. An else belongs to the nearest unmatched if above it, regardless of indentation.

Code
int age = 15;
boolean hasPermit = false;
if (age >= 15) {
  if (hasPermit) {
    System.out.println("May drive with an adult");
  } else {
    System.out.println("Get a permit first");
  }
} else {
  System.out.println("Too young");
}
Output
Get a permit first
Key points
  • Nested ifs put if, if-else, or if-else-if inside another.
  • The inner condition is checked only when the outer condition is true.
  • An if-else-if chain runs at most one branch: the first true one. A trailing else runs if none are true.
  • An else pairs with the closest unmatched if.
Watch out
  • Order matters in a chain. Testing score >= 70 first would give 95 a "C".
  • A run of separate if statements (no else) can run several branches.
Quick check
With x = 5, what prints?
if (x > 2)
  if (x > 8) System.out.print("A");
  else System.out.print("B");
Show answer
B. The else belongs to if (x > 8).