Reputation: 31
For the below code, I do not fully get why braces are not needed for the outer for loop? I know if we had them it would be fine but not fully getting why not having them is fine. You do not need braces if the loop's body is one statement. How is the outer's loop's body only one statement, technically is not the scope of the for loop including the inner for loop as well. Does this not mean that the outer for loop does not end till the inner for loop finishes, meaning the inner loop is a part of the outer for loop then right? In this case we should not be able to not use the braces I thought. I might be getting confused with what is consists of the outer for loops's body and the nested for loop.
class HelloWorld{
public static void main(String []args){
for(int i = 0; i < 10; i ++)
for(int j = 0; j < 5; j++)
{
System.out.println("Hello");
}
}
}
Upvotes: 3
Views: 104
Reputation: 968
The for and while loops as well as the if clause all control the following statement.
A statement can be a certain line of code or a block (code wrapped in curly braces). The for statement itself is defined as
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
Therefore the following statement can be any other statement (including a new for statement).
Your code rougly equals to
ForStatement (ForStatement Block)
The first for looks for the following statement, which is another for. It loops over the statement it found. The inner for finds a block as next statement and loops over the block. The block then can consist of multiple statements itself.
Also see (for loop without braces in java).
Upvotes: 1
Reputation: 2767
You outer loop does only process one statement - the inner for
. So everything else is not interesting for the outer loop and the inner loop could contain many lines since it does only belong to the inner loop (in this case marked with braces), for the outer loop only the one next line is important and it's ignoring the other lines. But the inner loop does not, so everything is fine since the outer loop does start the inner and the inner loop takes the rest.
But: It's more readable to use braces for the outer loop in this case.
Upvotes: 0
Reputation: 1
Because the insider loop is just one statement. You have to use the braces only when you have more than one statement inside the outer loop. so, the loop with its body is counted just as one statement.
Upvotes: 0