AP® Computer Science A · Unit 2 · Topic 2.4
Nested if Statements
A nested if is an if statement placed inside another if's body, so the inner test only runs when the outer one already passed. It filters a group of inputs down in stages, one condition at a time.
You nest ifs when a decision only makes sense after an earlier decision already came out true. Checking whether someone can drive solo isn't one fact, it's a chain: first are they over 16, and only if that holds, did they pass the road test. Side-by-side ifs would each run independently and couldn't express that second question depends on the first. Nesting puts the dependent question physically inside the body of the one it depends on.
Each layer of nesting shrinks the surviving group. Out of every possible input, the outer if keeps only the ones that pass its test and throws the rest out immediately, skipping the inner if entirely. Of those survivors, the inner if keeps only the ones that also pass its own test. By the time you reach code inside both ifs, you know both conditions are true, without writing a single compound condition.
Braces matter here more than almost anywhere else in control flow. Leave them off a nested if-else and Java attaches the else to the nearest unmatched if above it, no matter how you indented it, which can silently attach your else to the wrong branch. This is also where nested ifs connect to logical operators: two nested ifs where the inner body only runs when the outer condition held true are doing exactly what one if with && does. Compound conditions and nesting are two routes to the same filtering job, and seeing them as equivalent is what lets you simplify messy nested code later.
Key terms
- Nested if
- An if statement written inside the body of another if statement.
- Dangling else
- An else with no braces, which Java binds to the nearest unmatched if above it.
- Short-circuit filtering
- The way each nested condition eliminates inputs that fail it before any inner condition is even checked.
- Compound condition
- A single condition built from simpler ones using operators like && or ||.
Watch it explained
- How it worksHow does a nested if narrow the set of surviving inputs one test at a time?
- Worked exampleTrace a nested if that checks age over 16 and then whether a road test was passed.
- How it worksHow does an else attach itself to the nearest unmatched if when braces are left off?
- Ties togetherHow does a nested if do the same job as one compound condition joined by AND?
Check yourself
End of topic.