Grails Cookbook - A collection of tutorials and examples

Java 5 For Loop String Array

No matter how advanced programming will be in the future, the basics will always be important. Cornerstone are basic data structure such as String Array, which is very simple to understand and use. One typical thing we wish to do with a String Array is to loop through all of it's values. Below is an example on how to loop to all values of a String Array, using for loop introduced in Java 5.

Before Java 5

The way to use for loop to visit all the values of a String Array in Java uses an index to each item. Here is an example:

for (int i=0; i<arr.length; i++) {
    String item= arr[i];
    System.out.println( item );

This is a bit tedious and error prone. Accessing via index can lead to unwanted accidents. For example, mixing up counters when working with double loops. A counter meant for another array can be used in the current array that can lead to errors that are hard to see.

For Loop in Java 5

Since looping through values in an array is very common, Java 5 introduced a new for loop construct to easily do this. Here is an example which is the equivalent of the code above:

for (String item:arr) {
    System.out.println( item );

The code sample now does not use any index. It is understood that we want to visit all the values from the first item up to the last. This makes our code shorter and safer. All the values are visited one by one and assigned to the variable item, which is declared to be String. We assume that arr is a String Array.