The for
statement provides a compact way
to iterate over a range of values.
The general form of the for
statement
can be expressed like this:
for (initialization; termination; increment) {
statement
}
initialization is a statement that initializes the loop--its
executed once at the beginning of the loop.
termination is an expression that determines when to terminate the loop.
This expression is evaluated at the top of each iteration of the loop.
When the expression evaluates to false
,
the loop terminates.
Finally, increment is an expression
that gets invoked for each iteration through the loop.
Any (or all) of these components can be empty statements.
Often for
loops are used to iterate
over the elements in an array, or the characters in a string.
The sample shown below,
ForDemo
,
uses a for
statement to iterate over the elements of
an array and print them:
public class ForDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + " ");
}
System.out.println();
}
}