An enhanced for
loop (sometimes called a for each loop) is used to visit each element in an array or ArrayList
(or other data structure) without using an index. The lack of an index makes certain errors less likely, especially bounds errors. Code using enhanced for
loops may also be easier to read.
Enhanced for
loops in Java have limitations that must be understood. If in doubt about whether an enhanced for
loop is appropriate, use a regular for
loop or a while
loop.
Enhanced for
loop example with array of int
int[] nums = {7, 4, 10};
int sum = 0;
for(int n : nums)
{
sum += n;
}
System.out.println(sum);
The code segment prints:
21
The loop is read: for each int n
in nums
.
Each time the loop runs, n
is set to a copy of a value in nums
. The first time the loop runs, n
is 7
. The second time the loop runs, n
is 4
. The third time the loop runs, n
is 10
.
Enhanced for
loop example with ArrayList<String>
ArrayList<String> words = new ArrayList<String>();
words.add("catastrophe");
words.add("caterpillar");
words.add("dog");
words.add("cat");
for(String w : words)
{
if(w.indexOf("cat") == 0)
{
System.out.println(w);
}
}
The code segment prints:
catastrophe
caterpillar
cat
Enhanced for
loop limitations
Loop variable stores a copy
Array of primitive type
int[] nums = {7, 4, 10};
for(int n : nums)
{
System.out.print(n + " ");
n = -1;
System.out.println(n);
}
System.out.println(Arrays.toString(nums));
The code segment prints:
7 -1
4 -1
10 -1
[7, 4, 10]
Each iteration, the value of the variable n
is set to a copy of the value in the array. The statement n = -1;
sets the value of n
to -1
, as expected. Changing the value of n
to -1
has no effect on any value in the array.
Array or list of references
The behavior of enhanced for
loops with respect to arrays or lists of references is more complex. Understanding the behavior requires understanding how references to objects are stored. See Enhanced for loop exercises for detailed demonstrations.
If there is doubt about whether an enhanced for
loop is appropriate, use a different loop type.
Cannot structurally modify the list
ArrayList<String> words = new ArrayList<String>();
words.add("apple");
words.add("pear");
words.add("orange");
for(String w : words)
{
words.add(0, words.remove(0));
}
The code segment crashes with a ConcurrentModificationException
.
The statement words.add(0, words.remove(0));
removes the word at index 0
from words
and adds it back at index 0
. The list contains the same elements in the same order immediately after execution. In a regular for
loop (or a while
loop), this statement could be executed repeatedly without issue.
Statements that structurally modify the list being looped through in an enhanced for
loop cause the loop to crash on the next iteration. Structural modifications are operations that change the size. add
and remove
are structural modifications. get
and set
are not.
It does not matter if the structure modifications appear to cancel each other out, as in this example. Enhanced for
loops in Java are implemented using iterators. Additional (highly technical) details can be found in the Javadoc for ConcurrentModificationException.
Minor limitations
Enhanced for
loops do not provide an index as part of the loop. Although one can be created and maintained, it is generally easier to use a different loop type when access to an index is desired.
Enhanced for
loops do not provide easy access to more than 1 element within a single iteration. It is possible to store the value from the previous iteration; however, it is generally easier to use a different loop type.
Help & comments
Get help from AP CS Tutor Brandon Horn