Classic for statement

The for statement is similar to the while statement, but is more oriented to work with arrays or collections. Today, there are two for statement versions; classical (old) and another known as enhanced.

Syntax

It is based on the use of a counter variable, which often take the names "i" or "j" and is called index.

Syntax:

for(<initialization>; <condition>; <modification>)
	<instruction>

Using a block of instructions it would look like this:

for(<initialization>; <condition>; <modification>) {
	<sequence of statements separated by semicolons>
}

Normally, <initialization>, <condition> and <modification> work over the index. The <initialization> usually starts the index, the <condition> controls whether the index is in range and <modification> increments or decrements the index.

Let's look at an example:

Example of how to print from zero to nine

for (int i = 0; i < 10; i++) 
	System.out.println(i);

Let´s follow the loop:

  1. The index i is initialized to zero.

  2. Condition (0 <10) is evaluated and because it is true; System.out.println (i) is executed. "0" is printed on console

  3. i++ is executed, which leaves i being worth 1.

  4. Condition (1<10) is re-evaluated.

  5. At the end of the 10th repetition, i++ happens to be worth 10 and 10 <10 is false, so this ends the execution.

This example prints the numbers 0 to 9 to console. We can do exactly the same thing using while:

 int i = 0; // <inizialitation>
	while (i < 10) { // <condition>
	System.out.println(i);
	 i++; // <modification>
}

Example of countdown from ten to zero

In this example, the index starts in 10 and in each iteration it decrements by one.

The termination condition is i> = 0, so it will iterate until we get to zero included.

for (int i = 10; i >= 0; i--) 
	System.out.println(i);

Example of printing an array

The for statement is historically related to the handling of arrays. Here we can see a simple example, where we print the elements of the array numbers.

int[] numbers = { 34, 65, 23, 97, 23, 78, 33 };
for (int i = 0; i < numbers.length; i++) {
	System.out.print(numbers[i] + " ");
} 

Enhanced for statement

This statement is specially designed to iterate over arrays or collections of objects without using an index.

Syntax:

for(<item declaration> : <items collection>)
	<instruction>

Using a block of instructions it would look like this:

for(<item declaration> : <items collection>) {
	<sequence of statements separated by semicolons>
}

Example of how to print an array using the enhanced for statement.

int[] numbers = { 34, 65, 23, 97, 23, 78, 33 };
for (int item : numbers) {
	System.out.print(item + " ");
}

The item variable takes the value of each element of the array numbers. An index variable is not required.

Summary

In future tutorials we will take a look at examples of how to use the for statement in its two variants.