Java Statements, processing precedence ("dangling else")
Of course, the answer is in the Java Language Specification. The relevant section is section 14.5, "Statements", which describes exactly this case:
As in C and C++, the if statement of the Java programming language suffers from the so-called "dangling
else
problem," illustrated by this misleadingly formatted example:if (door.isOpen()) if (resident.isVisible()) resident.greet("Hello!"); else door.bell.ring(); // A "dangling else"
The problem is that both the outer
if
statement and the innerif
statement might conceivably own theelse
clause. In this example, one might surmise that the programmer intended theelse
clause to belong to the outerif
statement.
And finally:
The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an
else
clause belongs to the innermostif
to which it might possibly belong.
(emphasis by me)