The most structured Java loop is the
for loop, which repeats a section of code a fixed number of times.
for Statement
The for statement is used when the number of times the loop needs to be executed is known. There are two variations of the for loop. The first one is discussed in this section and is the traditional form. The for-each statement is the second form and was introduced in Java 5.
It is discussed in the at the bottom of this page. The for statement consists of the following three parts:
- Initial operation
- Terminal condition
- End loop operation
Following is the syntax of the
for
loop:
The body of a for loop is typically a block statement. The initial operation takes place prior to the first iteration of the loop and is executed only once. The end loop operations take place at the end of each execution of the loop. The terminal condition
determines when the loop will terminate and is a logical expression. It is executed at the beginning of each repetition of the loop.
Thus, the body of the for loop may be executed zero times if the first time the terminal condition is evaluated, it evaluates to false.
A variable is normally used as part of the initial operation, terminal condition, and end loop operation. The variable is either declared as part of the loop or is declared external to the loop. The following code snippet is an example of declaring a variable, i, as part of the loop. An example of using an external variable is covered in the The for statement and scope section:
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println();
In this example we used a single statement in the body of the loop. The variable
i
was assigned an initial value of 1 and is incremented by 1 each time the loop executes. The loop executed 10 times and produced 1 line of output. The statement, i++, is a more concise way of saying i = i + 1. The output should be the following:
1 2 3 4 5 6 7 8 9 10
The
for
loop repeats the
Statement
a number of times as determined by the
- initialization-expression,
- boolean-condition,
- update-expression:
- The
initialization-expression
initializes a loop control variable.
- The
boolean-condition
compares the loop control variable to some limit value.
- The
update-expression
updates the loop control variable before the next iteration of the loop.
Following is an example that uses a
for
loop to count up from one to ten: