Foreach Loops

Foreach loops are for loops specifically designed to be used with arrays, lists, and other data structures. Arrays and Lists - covered in the ArrayLists lesson - have a series of values. Foreach loops will go through the entire series, allowing the user to manipulate each individual value in a systematic way. Here is the syntax:

    for (int x : y) {

        ...

    }

The variable x is the given local variable which represents the current value in the data structure. The variable x must be the same type as the variables stored in the data structure. The variable y calls the data structure.

Here is an application of the foreach loop.

    int[] a = {0,1,2,3,4};

    for (int i : a) { 

        System.out.print(i + 1 + " "); // example code

    }

The above code will print “1 2 3 4 5 “.

You can do something similar with 2D arrays:

    int[][] array = {{1, 2}, {2, 3}, {3, 4}};

    for (int[] arr : array) {

        for (int i : arr) {

            ...

        }

    }

Lesson Quiz

1. On what type of array would the below for each loop work?

    for (int i : j) { }
a. Two dimensional String array
b. One dimensional String array
c. One dimensional int array
d. Two dimensional int array

Written by James Richardson

Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.