The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Learning the Java Language
Lesson: The Nuts and Bolts of the Java Language

The for Statement

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(in a .java source file), 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();
    }
}

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search