For Each Loop in Java 5
Compared to other changes in Java 5, this is a smaller change. The idea behind this change is to improve how we access collection elements and arrays. In this article, we see how the loop has improved over a period of time through different releases of Java. What are the advantages we get with new for loop? When is it not recommended to use this loop?
Let us see the ugly code to traverse through a collection. You must have written such a code by mistake in very early releases of Java.
import java.util.ArrayList;
import java.util.List;
public class UglyForLoop {
public static void main(String[] args) {
List list = new ArrayList(2);
list.add("First");
list.add("Second");
String str = null;
for(int count = 0; count < list.size(); count++){
str = (String)list.get(count);
System.out.println(str);
}
}
}
What is ugly about this? You must have spotted it by this time. If not, don't worry. In this code snippet, the traversing is done programmatically using 'count' variable instead of using the Iterator feature provided by Java. This code will be of help if you are manipulating the collection while traversing through it. But in general, this is not an elegant way of traversing through a collections. So which is the better way? You can see the difference in following code.
public class GoodForLoop {
public static void main(String[] args) {
List list = new ArrayList(2);
list.add("First");
list.add("Second");
String str = null;
for(Iterator itr = list.iterator(); itr.hasNext();){
str = (String)itr.next();
System.out.println(str);
}
}
}
In this example, the code has improved by usage of Iterator. It also looks neater and we have better control over the traversing process through collection. Still there is room for improvement. The Iterator variable itr appears thrice before you actually get the element out of collection. Just imagine a scenario where you have three nested loops on three different collections to handle. Means, there are nine such iterator objects references to confuse and lead to mistake. This problem is addressed through for-each loop in Java 5. First we see the changed code and then the benefits.
import java.util.ArrayList;
import java.util.List;
public class ForEachLoop {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(2);
list.add("First");
list.add("Second");
for (String str : list){
System.out.println(str);
}
}
}
This for loop has removed the iterator and has given access to the collection element at very first line of loop. Now, even if you have nested loops for collections, the code is going to be cleaner enough to stop you from committing mistakes.
Advantages of for-each Loop:
- Less error prone code
- Improved readability
- Less number of variables to clean up
Limitations:
- Cannot be used where the collection is to be altered while traversing/looping through
- My not be suitable while looping through multiple collections in parallel
Previous Next
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Don’t forget you sometimes just need Iterator in order to do modifications (e.g. delete elements) during the iteration. The Iterator interface supports generics so you can use a nicer version of it without having to cast:
public class GoodForLoop {
public static void main(String[] args) {
List list = new ArrayList(2);
list.add(“First”);
list.add(“Second”);
String str = null;
for(Iterator itr = list.iterator(); itr.hasNext();){
str = itr.next();
System.out.println(str);
}
}
}
Also, the first example can be modified to use generics and, since Java has nothing that allows one to iterate over two collections at a time, the “classic” version of the loop must be used to do so.
“This for loop has removed the iterator…” – the iterator is not called explicitly, but it is still used inside the foreach loop.