What is the problem of dangling-else?
When does it arise?
What is the default dangling-else matching, and how can it be overridden?

Single Choice
Views 25

Answer:

Question:

What is the problem of dangling-else?
When does it arise?
What is the default dangling-else matching, and how can it be overridden?


Answer:

🧩 Definition:

The dangling-else problem occurs in nested if statements when it is unclear which if a particular else belongs to.

It’s called “dangling-else” because an else seems to be “hanging” or “dangling” without a clear matching if.


âš™ī¸ When it arises:

It arises when if statements are nested without braces {}, like this:

if (condition1)
    if (condition2)
        System.out.println("Hello");
    else
        System.out.println("Hi");

💭 Ambiguity (The Problem):

In the above example, it’s unclear whether the else belongs to:

  1. the first if, or

  2. the second if

This causes confusion both for programmers and, in some languages, for compilers (though Java resolves it in a specific way).


✅ Default Matching in Java:

In Java (and most programming languages like C/C++), the rule is:

An else is always associated with the nearest unmatched if.

So, in the above example, the else belongs to the inner if.


đŸ› ī¸ How to Override (Remove Ambiguity):

You can use braces {} to clearly specify which if the else should belong to.

Example 1 – Default behavior (else belongs to inner if):

if (a > 0)
    if (a > 10)
        System.out.println("Greater than 10");
    else
        System.out.println("Less than or equal to 10");

Here, the else is matched with the inner if (a > 10).


Example 2 – Override using braces (else belongs to outer if):

if (a > 0) {
    if (a > 10)
        System.out.println("Greater than 10");
} else {
    System.out.println("Less than or equal to 0");
}

Now, the else clearly belongs to the outer if (a > 0).


🧠 Summary Table

Concept Explanation
Problem Name Dangling-else problem
Occurs When Nested if statements are written without braces
Default Matching Rule else matches the nearest unmatched if
Solution / Override Use braces {} to make the pairing clear

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.