Java: for each loop

The following code iterates over the elements in iterable:

for (Type elem : iterable) {
    // process elem
}

Where iterable can be

Behind the scenes

In case iterable is an array, the above snippet is equivalent to

for (int i = 0; i < iterable.length; i++) {
    Type elem = iterable[i];
    // process elem
}

In case iterable is an Iterable, it's equivalent to

Iterator<Type> iter = iterable.iterator();
while (iter.hasNext()) {
    Type elem = iter.next();
    // process elem
}

Auto boxing

Thanks to auto (un)boxing, you can for instance use an int to iterate over a list of Integer:

Example:

List<Integer> ints = new ArrayList<>();
// ...
for (int i : ints) {
    // ...
}

Optional Braces

For single statement bodies, the braces are optional, just as with if and while statements.

These two snippets are equivalent:
for (int i : arr) {
    System.out.println(i);
}
System.out.println("done");
for (int i : arr)
    System.out.println(i);

System.out.println("done");

The official style guide does however madate the use of braces for safety.

Accidental semicolon

There should not be a semicolon after the loop declaration:

for (…); { … }

See Beware of accidental semicolons in while and for loops!

Comments

Be the first to comment!