Comp 110 for-each Loop Statement

for-each Loop Syntax

A common practice in programming is using an iterator to work through data stored in a collection. A for-each loop can be used to do this succinctly.

for (T item : Iterable<T> ){
  //for-each body
} 

A for-each loop iterates through a set of data (list, array, array list, map, etc.) until it does not have any more values in the list. It works the same way that a while loop asking if the list if it has another value (hasNext) works.

A for-each loop essentially reads "For each item in a given set of data do whatever is in the body of this loop."

ArrayList<String> ourArray = ...;
for( Object o : ourArray) {
    //for-each body
}

Practice Problem:

What would the following code output?

int[] example = { 1, 3, 5, 7};

for(int a : example){
    System.out.print(a + " ");
}

Output:

1 3 5 7

The for-each loop would print each item in the array. (Note: The print statement does not create a new line. Here, we concatenate a space between each number.)