For statement

The for statement

The for loop is used when you know in advance how many times the codes should run.

Syntax

The following program prints the numbers 0 through 4 to standard output:

Run The Application

Right click to the ForDemo class; select Run As -> Java Application.

Output

Infinite loop

For enhancement

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhancement for statement, and can be used to make your loops more compact and easy to read.

The following code uses the enhanced for to loop through the array.

Run The Application

Right click to the EnhancedForDemo class; select Run As -> Java Application.

Output