Unit 2 Cycle 2 Day 22: Error: Dangling Else

Unit 2 Advanced (Cycle 2) Day 22 of 28 Advanced

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.

int x = 5; int y = 10; if (x > 3) if (y > 20) System.out.print("A"); else System.out.print("B");

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.

Review this topic: Section 2.3 — If-Else Statements • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.