Dangling else problem in Java

The else statement in the code below is dangling because it is not clear which if statement the else statement is associated with. An else statement is always associated with the immediately preceding if. Using braces makes your code clearer.

if (a > 0 || b < 5)
    if (a > 2)
        System.out.println("a > 2");
        System.out.println("a < 2");

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.