for loop without braces in java

若如初见. 提交于 2019-12-01 15:29:07

That is because the default scope of an iteration in your case is the only line following it, something equivalent to -

for(i=1, j=0;i<10;i++) {
    j += i;
}
System.out.println(i);

Hence the entire loop is iterated and since after that the value of i==10, that is your output in the second case.


In the first case, it's pretty obvious that the value is printed with each iteration and hence 1 to 9(less than 10) :

for(i=1, j=0;i<10;i++){
    j += i;
    System.out.println(i);
}

The for loop, the while loop, and the if statement (ignoring else) all control a single Statement:

for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

while ( Expression ) Statement

if ( Expression ) Statement

That statement may be a Block, i.e. braces {} with multiple statements.

So, this code is all the same:

for(i=1, j=0;i<10;i++)
j += i;
System.out.println(i);
for(i=1, j=0;i<10;i++)
    j += i;
    System.out.println(i);
for(i=1, j=0;i<10;i++)
    j += i;
System.out.println(i);
for(i=1, j=0;i<10;i++) {
    j += i;
}
System.out.println(i);

The first two are very bad, because they hide (misrepresent) the code structure.

Many people advocate always using blocks, to prevent confusing and coding errors.

In the second example, the output is outside the for loop. A for loop without curly brackets only includes the following statement.

Loop without braces apply only to the next statement

So :

 for(i=1, j=0;i<10;i++)
    j += i;
System.out.println(i);

is equivalent to :

 for(i=1, j=0;i<10;i++){
        j += i;
 }
    System.out.println(i);

i is defined out of loop scope and is incremented after the last loop so it has value of 10

The first statement contains a block of code. A block of code is handled as one unit.

To create a block of code you should insert statements between curly braces.

loop and conditional expressions are handling only the first statement under them, if no block of code specified.

Therefore:

// Both statements handled 10 times
for(i = 1, j = 0; i < 10; i++) {
    j += i;
    System.out.println(i);
}

// Only the first statement handled 10 times, the second one is out of scope of the loop
for(i = 1, j = 0; i < 10; i++)
    j += i;
System.out.println(i);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!