From what I know, the scope of a ‘for’ loop, without a set of parentheses after it, is just one statement. Right?
So how come this code:
for(int x = 0; x < 3; x++)
if(x < 2)
System.out.println("hello");
System.out.println("world");
gives the output:
hello
hello
world
Is the statement in the if is also considered part of the for loop? Of course it is, but my question is: Why?
Does what actually is that that the scope is a block right after for statement because the above code when modified like this:
for(int x = 0; x < 3; x++)
if(x < 2) {
System.out.println("hello");
System.out.println("world");
}
gives the output:
hello
world
hello
world
Most of the answers are about explaining the flow control in the above code. I already know that. My question was about the rule of the for loop scope.
Is the rule actually that: the scope of an braceless for loop is the next block of statements immediately after it?
You should read Braceless if considered harmful. This post was specifically made because of examples just like this; the confusion that brace-less control flow statements can leave you scratching your head for quite a while, especially with misleading indentation (such as in your example).
The code you pasted is equivalent to the following,
As you can see, the loop iterates three times; the first two, it will print
"hello". After the loop completes, it will print"world".The reason this works is clear in reading Chapter 14 of the Java Language Specification. In fact, it makes sense to think of blocks as statements, as per §14.5.
Looking at the descriptions of
if(§14.9) and basicfor(§14.14.1), we see both merely take a statement; in this case, we can see ourforstatement containsifstatement, which itself encapsulates yourprintln("hello")statement. Following theforstatement, you then have yourprintln("world")statement.Here, we see the
forstatement body is theifstatement, which encapsulates a block that contains 2 statements, namely both yourprintlnstatements. Note that this is indeed not the same as the former.Hopefully this clears things up for you.