Topic 2.4 — Nested if Statements

Goal: trace and write nested if statements, and understand how the structure of nesting affects which blocks run.

The big idea

A nested if is an if statement inside another if (or inside an else block). Nesting lets your code make a second decision only after a first decision is made.

Rule: always evaluate conditions from the outside in.

Why nesting exists

  • You want to check a “big” condition first, then only do extra checks if it passes.
  • You want multi-step decisions (like login → then permissions).
  • You need logic like “if A is true, then check B; otherwise do something else.”

Nested if inside if

int score = 85;
boolean didProject = true;

if (score >= 70) {
  if (didProject) {
    result = "pass";
  } else {
    result = "incomplete";
  }
} else {
  result = "retry";
}

The inner if only runs if score >= 70.

Nested if inside else

Sometimes you nest because you only want extra checks in the “failed” case.

if (x >= 0) {
  type = "nonnegative";
} else {
  if (x % 2 == 0) {
    type = "negative even";
  } else {
    type = "negative odd";
  }
}

The “dangling else” rule (super tested)

An else always matches the closest unmatched if. This can surprise people when braces are missing.

Risky (no braces)

if (a)
  if (b)
    x = 1;
  else
    x = 2;

The else matches if (b), not if (a).

Clear (with braces)

if (a) {
  if (b) {
    x = 1;
  } else {
    x = 2;
  }
}

Same logic, but now there’s no ambiguity.

Nesting vs. compound conditions

Sometimes you can replace nesting with && or ||… but not always.

Approach When it’s good
Nesting When the second check should only happen after the first is true
Compound condition When you can express the decision as one boolean expression

Common mistakes

  • Missing braces causes the else to attach to the wrong if.
  • Tracing incorrectly: you must re-check which blocks actually run.
  • Over-nesting when a simple compound condition would be clearer.

Exam mindset

  • Trace from the outside in. If the outer condition is false, inner blocks don’t run.
  • Assume else matches the nearest unmatched if unless braces force otherwise.
  • Braces make logic unambiguous—AP questions often test what happens without them.

Quick self-check

  1. What does “nested if” mean?
  2. When does the inner if run?
  3. In code without braces, which if does an else match?
  4. Why might nesting be safer than a compound condition sometimes?
  5. Why do braces matter even if the logic is “simple”?

← Back to Unit 2 topics