Dove's LibraryDove's Library

2.4 - Nested if Statements

You can put if, if-else, or if-else-if statements inside other if statements. That’s called nesting.
The inner condition only even gets checked if the outer condition was true first. If the outer one is false, Java never bothers looking at the inner one.
if (age >= 18) { if (isRegistered) { System.out.println("You can vote."); } else { System.out.println("You need to register first."); } } else { System.out.println("You're too young to vote."); }
Tracing it: if age is 20 and isRegistered is false, the outer condition is true, so Java checks the inner one. It’s false, so this prints “You need to register first.” If age is 15, Java jumps straight to the outer else and prints “You’re too young to vote.” without ever checking isRegistered.
Multiway selection (if-else-if) is what you use when you’ve got a series of conditions to check, each with its own code to run. Java checks them in order and runs the code for the first one that’s true, then stops, it won’t check the rest even if they’d also be true. If none of them are true and there’s a trailing else, that runs instead.
if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else { System.out.println("F"); }
The order of the conditions matters. Each else if only gets checked when every condition above it was false, which is why grade >= 80 here really means “80 to 89.” If the conditions were in the opposite order (checking grade >= 70 first), a 95 would print C, since grade >= 70 would be the first true condition.
Compare multiway selection with a list of separate if statements. Separate if statements are each checked on their own, so more than one body can run:
int grade = 95; // multiway selection: only the first true branch runs if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } // prints A // separate if statements: every true condition runs if (grade >= 90) { System.out.println("A"); } if (grade >= 80) { System.out.println("B"); } // prints A, then B
If there’s no trailing else and none of the conditions are true, nothing in the whole statement runs.

AP® is a registered trademark of the College Board, which is not affiliated with Dove's Library and was not involved in the production of, and does not endorse, this website.

Providing free, high-quality AP notes to help students succeed, earn college credit, and reach their educational goals, ensuring everyone has access to the resources they need.

© 2026 Standard Learning Group, Inc., which operates Dove's Library. All rights reserved.