Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java if-if-else behavior

I wrote a simple if/else in my code which worked fine. Later I added another level of if under the first, and was baffled by its behavior. Here's very simple code to recreate the situation:

public static void main(String[] args) {
    boolean a = true;
    boolean b = false;

    if (a)
        if (b)
            System.out.println("a=true, b=true");
    else
        System.out.println("a=false");
}

It returns "a=false", even though a is true!

It turns out the else binds with the nearest if, although I have not found it documented anywhere, and eclipse does not highlight the mismatched indentation levels as an error (although it does correct it when formatting the file).

A very, very strong argument for using braces!

Where is the binding order of else/if documented?

And as a challenge,

Is there a way to make the above code do what the indentation makes you expect without adding braces?

like image 599
Jeff Snider Avatar asked Nov 26 '22 21:11

Jeff Snider


1 Answers

Is there a way to make the above code do what the indentation makes you expect without adding braces?

No. Because Java is not Python, and compiler doesn't work based on what's on your mind. That is why you should always use braces.

Clearly the else is a part of the inner if, and hence the result is expected. This is evident from JLS §14.5 - Statements

like image 57
Rohit Jain Avatar answered Dec 15 '22 05:12

Rohit Jain