Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...