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.
- 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.
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");
}OutputBChain vs. separate ifs
Separate if statements are all checked, so several can run. A chain runs at most one.
Codeint 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();OutputABC 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.
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");
}OutputGet a permit first- Nested ifs put
if,if-else, orif-else-ifinside another. - The inner condition is checked only when the outer condition is true.
- An
if-else-ifchain runs at most one branch: the first true one. A trailingelseruns if none are true. - An
elsepairs with the closest unmatchedif.
- Order matters in a chain. Testing
score >= 70first would give 95 a "C". - A run of separate
ifstatements (no else) can run several branches.
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).