Given the following valid piece of code:
Boolean a = false;
if (a)
System.out.println("A");
else
System.out.println("!A");
According to the documentation, if
including its condition and inner statement
is also a statement
. For example:
if (b){
System.out.println("B");
}
is a statement
.
However, when we are going to replace an existing statement with another one, it shouldn't touch the overall logic, right? Assuming we replace the (Expression)-statement
with the if-statement
above :
Boolean a = false;
Boolean b = false:
if (a)
if (b){
System.out.println("A and B");
}
else
System.out.println("!A");
Java Compiler will interpret the code example as follows (full braces for explanation):
Boolean a = false;
Boolean b = false:
if (a){
if (b){
System.out.println("A and B");
} else {
System.out.println("!A");
}
}
which is not the initial logic.
So why is exchanging one statement against another changing the logic?
From the example one can clearly say, that the problem is just about the braces, but I cannot find information about the way java is exactly dealing with this, if braces are omitted.
Is there anything written down about this behavior? Why does java prefer to connect the else
to the more recent if
, rather than the first if
it encounters while parsing?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With