In Java, the for keyword is used to iterate over a range of values, items of an array or a collection. The code that uses for keyword is called as for loop.
In Java, there are two types of for loop: classic for loop and enhanced for loop (for-each).
Syntax of the classic for loop is as follows:
for (initialization; terminate condition; incrementation) {
// statements
}
where:
The following code example iterates over a range of integer numbers from 0 to 9 and output the current number to the standard output:
for (int i = 0; i < 10; i++) { System.out.println("Number: " + i); }
The enhanced for loop (also known as for-each) has been introduced since Java 5.
This kind of for statement is a convenient way to iterate over an arry or a collection. Syntax of enhanced for loop is as follows:
for (T var : collection<T> or T[] array) {
// statements
}
where T is actual type of the array or collection, and var is name of the variable refers to the current item in the collection or array. The following code example uses enhanced for loop to iterate over an array of integers:
for (int number : nums) { System.out.println("Number: " + number); }
And the following code iterates over an collection of Strings:
Collection<String> names = new ArrayList<String>(); names.add("Tom"); names.add("Bill"); names.add("Jack"); for (String name : names) { System.out.println("Name: " + name); }
See all keywords in Java.