Dangling Else Problem in JavaThe 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 ProblemThere are the following two ways to avoid dangling else problem:
Example of Dangling else ProblemDanglingElseExample.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. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India