The most general form of the for loop is also a holdover from the C language:
for ( initialization; condition; incrementor )
statement;
The variable initialization section can declare or initialize variables that are limited to
the scope of the for statement. The for loop then begins a possible series of rounds in
which the condition is first checked and, if true, the body statement (or block) is executed.
Following each execution of the body, the incrementor expressions are evaluated
to give them a chance to update variables before the next round begins:
for ( int i = 0; i < 100; i++ ) {
System.out.println( i );
int j = i;
...
}
This loop will execute 100 times, printing values from 0 to 99. Note that the variable j
is local to the block (visible only to statements within it) and will not be accessible to
the code “after” the for loop. If the condition of a for loop returns false on the first
check, the body and incrementor section will never be executed.
You can use multiple comma-separated expressions in the initialization and incrementation
sections of the for loop. For example:
for (int i = 0, j = 10; i < j; i++, j-- ) {
...
}
You can also initialize existing variables from outside the scope of the for loop within
the initializer block. You might do this if you wanted to use the end value of the loop
variable elsewhere:
int x;
for( x = 0; hasMoreValue(); x++ )
getNextValue();
System.out.println( x );
0 comments:
Post a Comment