Grails Cookbook - A collection of tutorials and examples

Iterate Through String Array in Java

A String Array is a data structure that holds several String values. The number of String elements is fixed and can't be changed throughout the lifetime of the array object. One common thing that we wish to do with String Array is to go through all the data it contains and process individually. Below contains examples on how to iterate through String Array in Java.

Iterate Through String Array in Java (Version 1.4 and below)

It is more cumbersome to go through all the items of an array prior to the release of Java 5. The usual way is to have a for loop with a counter and to retrieve an item using an index. Below is a simple example:

/**
 * A simple example that iterates through a String Array prior to Java 5.
 */
public class IterateStringArraySample
{
    public static void main(String[] args)
    {
        String[] nameArray= {"John", "Paul", "Ringo", "George"};
        int numberOfItems = nameArray.length;
        for (int i=0; i<numberOfItems; i++)
        {
            String name = nameArray[i];
            System.out.println("Hello " + name);
        }
    }
}

Notice that we used the length attribute of the String array to get the number of items we have. Then we use a for loop to go through all the valid index from 0 upto length - 1. This is because Java is 0 based index language, which means index usually begins with 0 rather than 1. We then can retrieve an item from the array by retrieving at a particular index (E.g. String name = nameArray[i];). The output of the code above will show the following:
Hello John
Hello Paul
Hello Ringo
Hello George
The problem with this approach is that the code is quite long. Accessing items using index is also prone to error. If we have a typographic error, we might use a wrong index and raise the dreaded NullPointerException!

Iterate Through String Array in Java (Version 5 and above)

Since the release of Java 5, a better way of looping through items in a String Array has been supported. This is because looping through arrays is so common in most situation. The approach in Java 5 is cleaner, shorter, and less error prone. Below is a modified version of the code above that gives the same output:

/**
 * A simple example that iterates through a String Array (Java 5 and above).
 */
public class IterateStringArraySample
{
    public static void main(String[] args)
    {
        String[] nameArray= {"John", "Paul", "Ringo", "George"};
        for (String name:nameArray)
        {
            System.out.println("Hello " + name);
        }
    }
}

Notice that we don't need to know the size of the array nor access items using index. The code is much shorter and easier to read. There is also less chances of raising any RuntimeException using this way.