Enhanced for loop

Primordial for loop over an array

for (int i = 0; i < arr.length; i++) {
  // code here that uses i, e.g. arr[i];
}

This is the traditional way to loop over an array.

Inside the loop we can use i to get the current element.

We can also use i to know what position we are on.

Enhanced for loop over an array

for (String s : arr) {
  // code here that uses s
}

We get to process each element as s but the code doesn’t know what position it came from.

Use this unless you specifically need to know the index or if you need to modify the array by assigning back to the same position.

Equivalence

for (String s : list) {
  // code here that uses s
}

is basically equivalent to:

for (int i = 0; i < arr.length; i++) {
  String s = arr[i];
  // code here that uses s
}

Except we don’t have access to i in the enhanced for loop. So we can’t write code that depends on an element’s position in the array.

The point

In general we should use the enhanced for loop when we can.

It make certain kinds of bugs impossible.

And, more important, it makes code easier to read: if we see an enhanced for loop we know it’s a simple loop. It’s not modifying the array elements and it’s not accessing anything more than one element at a time.

But for some algorithms we need a traditional for.

boolean isSorted(int[] arr) {
  for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] > arr[i + 1]) {
      return false;
    }
  }
  return true;
}

This algorithm depends on accessing two elements of the array per iteration so it needs access to the index variable.