Dangling Else Problem in Java

The dangling else problem is an ambiguity of language interpretation. In programming, we can write conditionally executed code in the following two forms:

  • if-then form
  • if-then-else form

The problem rarely occurs while we deal with the nested if-else statement. It is an ambiguity in which it is not clear which if statement is associated with the else clause. For example, if X then if Y then E1 else E2. It is not unacceptable in programming.

From the above statement, it is clear that there are two if statements and a single else statement. But it is not clear which if statement is associated with else statement.

The problem is known as the dangling else problem.

Sometimes, the problem leads to a serious problem that may interpret the wrong result.

A Solution to Dangling Else Problem

There are the following two ways to avoid dangling else problem:

  • Try to design non-ambiguous programming.
  • The dangling else problem can be resolved by using the braces and indentation.
  • It is good to use if-else if-else It gives a clear view and understanding, i.e. which else statement is associated with which if statement.

Example of Dangling else Problem

DanglingElseExample.java

Output 1:

Enter a number: 200
The number is more than 100.

Output 2:

Enter a number: -200
The given number is negative.

Output 3:

Enter a number: 90

We observe that in the third execution, the program is not able to decide what to print on the console. It is an ambiguity that is known as the dangling else problem.