Java declaring iterator outside for loop
You can with:
for(; i<11; i++){
System.out.println("Count is: " + i);
}
But the scope of i
is different. i
will now exist outside of the loop.
You can. However you would simply have a blank ;
in where the initialization usually goes:
int i = 1;
for(; i<11; i++){
System.out.println("Count is: " + i);
}
The difference of this is that the scope of i
is now broadened to outside of the loop. Which may be what you want. Otherwise it is best to keep variables to the tightest scope possible. As the docs for the for
loop say:
declaring them within the initialization expression limits their life span and reduces errors.
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
What is really happening in the for loop that
BasicForStatement:
for ( ForInit ; Expression; ForUpdate )
Initialization need a statment as the docs says
If the ForInit code is a list of statement expressions
From Java Docs
So in this code
for(i; i<11; i++){
System.out.println("Count is: " + i);
}
i
is not a statment, it is just a variable. So what is a statment?
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).
Assignment expressions Any use of ++ or -- Method invocations Object creation expressions
Whit this knowlodge you can work any for loop if you know what is statemnt for example this for loop works
int i = 1; // Initializated
for(i++; i<11; i++){ // Whit a statemnt
System.out.println("Count is: " + i);
}
and the output will be :
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10