Unit 2 Cycle 2 Day 22: Error: Dangling Else
Share
Error: Dangling Else
Section 2.3 — If-Else Statements
Key Concept
The dangling else problem occurs when an else could logically pair with either of two if statements. In Java, an else always pairs with the nearest preceding unmatched if, regardless of indentation. So if (a) if (b) x(); else y(); means the else pairs with if (b), not if (a). The AP exam uses misleading indentation to make it appear the else belongs to the outer if. Always match else with the closest if that does not already have an else.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) B
The else binds to the nearest if, which is if (y > 20), not if (x > 3). So: x > 3 is true (enter). y > 20 is false, so the else prints "B". The indentation is misleading.
Why Not the Others?
(A) y > 20 is false (10 is not > 20), so "A" is not printed.
(C) Only one branch of the inner if-else executes.
(D) x > 3 is true, so the inner if-else is reached. The else branch prints "B".
Common Mistake
The "dangling else" problem: an else always matches the nearest unmatched if, regardless of indentation. The indentation suggests the else matches the outer if, but Java pairs it with the inner if.
AP Exam Tip
The AP exam loves dangling else questions. Always match each else with the closest preceding unmatched if. Use braces to make intent clear.