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:
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:
Example of Dangling else Problem
Enter a number: 200 The number is more than 100.
Enter a number: -200 The given number is negative.
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.