■ All three parts of a for statement are optional - meaning the initialization, the logical test, and the update. Any part or parts can be omitted. i.e. This code with no parts will loop forever:
for( ; ; ) do something;
■ You must provide one of the following to end the loop if you leave out the optional logical test in the middle:
1 - a break statement, or
2 - a call to System.exit(..), or
3 - throw an exception.
■ You must increment the test variable yourself if you choose to leave out the update expression at the end. i.e.
for ( int x = 0; x < 5; ) { //
note the missing update expression
// do something here
x += 1; //
update the variable manually
System.out.println( "Loop counter is
" + x ); // x is still in
scope here so it can be referenced
}
■ Multiple initialization and update expressions are allowed.
These must be separated by commas, must be all of the same type, and must not repeat the type. i.e.
for ( int x = 0, y = 0, z = 0; x < 5; x++, y++, z++ ) initializes and updates three int variables
■ You cannot provide the declaration of a variable outside the for expression and then perform its creation inside the expression. i.e.
int
y;
for ( int x = 0, y = 0; x < 5; x++ ) will not compile because of y being declared outside.
■ You cannot reference initialization variables outside their for loop.
The scope of initialization variables ends at the end of the loop code. i.e.
The last statement's reference to x here will not compile:
for
( int x = 0; x < 5; x++ )
{
// do things in loop
}
System.out.print(
"Loop counter is " + x ); //
x is being referenced out of its scope here