问题
Normally in JAVA if an IF statement doesn't have curly brackets can have only one line that is executed when IF condition is met, however if another IF block (inner IF) follows the initial IF, then no error is triggered and there are more lines. How is this possible?
Example
if (true)
if (true)
System.out.println("true");
else
System.out.println("false");
回答1:
Normally in JAVA if an IF statement doesn't have curly brackets can have only one line that is executed when IF condition is met,
Correction. An if
statement without braces can have only one statement that is executed when the condition is met. And the syntax of if
goes something like
if (<condition>) <statement>; [else <statement>;]
That is, if there's an else
, it's part of the if
. It's all one statement.
The reason there's no error is because there's no ambiguity here. (Well, not to the compiler, anyway.) Since the else
is part of the if
, it goes with the closest if
. So with proper indenting, you have
if (true)
if (true)
System.out.println("true");
else
System.out.println("false");
回答2:
No errors because it equals to
if (true) {
if (true) {
System.out.println("true");
}
else
{
System.out.println("false");
}
}
And a valid syntax.
But please always use {}
otherwise, it's very hard to understand where the if
block ends exactly.
回答3:
That's because your outer if
block really contains a single statement.
If inner
if
condition is true, the outerif
is equivalent to:if (true) System.out.println("true");
And if, inner
if
condition iffalse
, it is equivalent to:if (true) System.out.println("false");
Still, it is really a bad idea to omit the curly braces around if-else
or loops for that matter, and specially doing this with nested block, can turn evil. Just because it can be done, doesn't mean you should do it.
To see how the nested if
blocks without braces can grow ugly, and often lead to mistakes, consider this code, what do you think the output should be?
boolean b = true;
boolean b2 = false;
if (b)
if (true)
System.out.println("true");
if (b2)
System.out.println("Hello");
else
System.out.println("false");
回答4:
consider this IF statement as:
if(true) {
if(true) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
if first IF
is true
it goes to next statement, here next statement is also a IF
and also true
therefore it executes statements in it. If suppose it is false then it search for else
end executes statements in else
. So all statement are got covered and no error scenario occurs.
来源:https://stackoverflow.com/questions/18160602/why-an-if-block-is-allowed-inside-another-if-that-doesnt-have-curly-brackets-in