THE WORLD'S LARGEST WEB DEVELOPER SITE

Java for Keyword

❮ Java Keywords


Example

Print the numbers 0 to 4:

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

Run example »


Definition and Usage

The for loop loops through a block of code a number of times.

From the example above:


More Examples

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

The following example outputs all elements in the cars array, using a "for-each" loop:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

Run example »


Related Pages

Read more about for loops in our Java For Loop Tutorial.


❮ Java Keywords