Low Orbit Flux Logo 2 D

Java For-Each Loop

Since Java 5.0 it has been possible to use a for-each loop in Java. This is something that people tend to take for granted in other languages. This makes code cleaner and more readable than using a regular for loop. It also reduces the chances of introducing a bug into your code.

Answer: Using a for-each loop in Java is very easy. The basic syntax looks like this:

int[] a = new int[] {1, 2, 3, 4, 5};
for (int i: a) {
    System.out.println(i);
}

If you just want to iterate over an array or collection, this should make things much easier.

Here is an example showing how to loop over an array of chars and an array of ints:

class Test1 {
    public static void main( String args[] ) {
        char[] a = new char[] {'a', 'b', 'c', 'x', 'y', 'z'};

        for (char i: a) {
            System.out.println(i);
        }

        int[] b = new int[] {1, 2, 3, 4, 5};

        for (int i: b) {
            System.out.println(i);
        }
    }
}