TOPIC 2.4 · STUDY

Nested if Statements

An if can sit inside another if. The inner condition is tested only when the outer condition is true. An else pairs with the nearest unmatched if, not with an earlier outer if, unless braces say otherwise.

2.4.A

Nested if statements

A nested if places one if inside another. The outer condition runs first. Only when that outer condition is true does the program reach the inner condition. If the outer condition is false, the whole inner if is skipped, including any else that belongs to that inner if.

When an else sits next to two if headers, Java does not use indentation to decide ownership. The else pairs with the nearest unmatched if above it. Braces can change that pairing by closing the inner if before the else begins.

int battery = 40;
if (battery > 20)
    if (battery > 80)
        System.out.print("full");
    else
        System.out.print("ok");
// The else pairs with if (battery > 80), the nearest unmatched if.
// With battery 40: outer true, inner false, so ok prints.
Outer condition at the top. Its true path reaches an inner condition. Its false path skips the inner test entirely.

The inner condition sits on the outer true path. A false outer result never reaches that inner test.

Key points

  • An if can nest inside another if.
  • The inner condition runs only when the outer condition is true.
  • A false outer condition skips the inner if and that inner if's else.
  • An else pairs with the nearest unmatched if, unless braces say otherwise.
  • Indentation alone does not change which if an else belongs to.

else pairs with the nearest unmatched if.

Practice this topic