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\'
First and foremost, best advice is to always use braces!
Naturally, every else statement is attached to the nearest if-statement and this is evident from this link and this is why your code behaves this way. The compiler cares nothing about indentation.. You can write your entire code on one line, it'd still work as long as its syntactically correct.
Also, if you want the output you expected, nesting an if-statement inside another if-statement (with no else-statement) is a primitive practice; this can simply be done with the &&
operator like this:
if (a && b)
System.out.println("a=true, b=true");
else
System.out.println("a=false");
You'd have gotten your desired output. I hope this helps.. Merry coding!
It is clearly stated in Language specification 14.5. Statements:
Java programming language suffers from the so-called "dangling else problem,
Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not.
Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause.
It is documented in Section 14.5 of the Java Language Spec:
The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement.
The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong. This rule is captured by the following grammar:
Is there a way to make the above code do what the indentation makes you expect without adding braces?
I would go:
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (!a)
System.out.println("a=false");
else if(b)
System.out.println("a=true, b=true");
}
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a && b)
System.out.println("a=true, b=true");
else if (!a)
System.out.println("a=false");
}
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