Java if-if-else behavior

if-statement, java

Solution

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

Problem

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?

Original source

Related problems