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).

 

1. Java Classic for loop

Syntax of the classic for loop is as follows:

for (initialization; terminate condition; incrementation) {

    // statements

}

where:

    • initialization: contains code that initializes the loop, usually by declaring a counter variable. This code is executed only once.
    • terminate condition: contains code that checks for a condition to terminate the loop. This code is executed every iteration, if the codition is met, the loop is terminated.
    • incrementation: contains code that increments value of the counter variable. This code is executed every iteration.
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);
}
 

2. Java Enhanced for loop

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.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment