Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Statements, processing precedence ("dangling else")

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?

like image 506
dognose Avatar asked Aug 18 '15 15:08

dognose


1 Answers

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 inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if 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 innermost if to which it might possibly belong.

(emphasis by me)

like image 151
Marco13 Avatar answered Oct 21 '22 10:10

Marco13