Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

if statement - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...