Java for Loop Iteration Syntax

Posted September 9, 2004 by Rex in Java programming

The for loop provides a simple mechanism for repeating a code block a fixed number of times or for iterating through a set of values.

The generic syntax for a Java for loop is as follows:

for ( {initialization}; {exit condition}; {incrementor} )

For example, to execute a simple loop five times, printing out the iteration number each time through the loop, use the following syntax:

for ( i=1; i<6; i++ ) { System.out.println(i); }

In this example, the loop starts with an initialization of the (int) variable i to the value 1. Each time the loop iteration starts, the exit condition is evaluated (Is i less than 6?); and if true, it continues. When the loop iteration is complete, the incrementor code is executed (i++ means increment the variable i by one). The loop continues until the exit condition is met (when i is equal to or greater than 6), so the code block will be executed for i values of 1, 2, 3, 4, and 5.

The exit condition code can be more complex as needed because it is computed each time through the loop. Thus, the condition can be based on variables which may change during the loop iteration. To run a code block on each value of an array, the loop condition could be i < array.length.

The incrementor code can also be more complex, essentially any valid Java code. Another simple example would be a decrementor using i-- which would subtract one from the variable i each time through the loop.

The Conversation

Follow the reactions below and share your own thoughts.