How does Enhanced for loop works in Java?

It's a long time since JDK 1.5 introduced the enhanced for loop, almost 12 years ago in the year 2004, but still many Java developers don't know basics of enhanced for loop, also known as for each loop in Java. The enhanced for loop provides the cleanest way to loop through an array or collection in Java, as you don't need to keep track of counter or you don't need to call the hasNext() method to check whether there are more elements left. The key point, which many Java developer doesn't know about the enhanced for loop is that you can use any Object which implements the Iterable interface on for (: ) construct, you can even use enhanced for loop to loop through the array. Since JDK 8 also introduced a forEach() function to provide looping functionality, don't confuse when I say for each loop with that. In this article, we'll see how enhanced for loop works and couple of important points related to it.

Btw, Java 5 introduced several useful features along with enhanced for loop e.g. Generics, Enum, Concurrency API, Variable arguments, Static import, covariant method overriding etc. Nowadays, it's expected from a Java developer to know all these features by heart. If you feel you lack in any of these then I suggest reading Cay S. Horstmann's Core Java for the Impatient book. One of the best book to fill your gap in Java. It also covers Java SE 8.

How for each loop works in Java

How enhanced for loop works in Java

Suppose, you want to loop over a List in Java, you can write following code to accomplish that using the enhanced for loop:

List<String> listOfCities = new ArrayList<>(Arrays.asList(new String[]{"USD", "GBP", "INR"}));

for(String city : listOfCities){

This is equivalent to the following code because enhanced for loop is nothing but a syntactic sugar over Iterator in Java:

for (Iterator<String> i = listOfCities.iterator(); i.hasNext();) {
   String city =;

Of course, enhanced for loop approach is much cleaner and readable but it is also more limited as you cannot remove elements while iterating, there is no reference to the iterator to call the remove() method, and if you call remove() method of List then you will end up with ConcurrentModificationException in Java. To avoid this dreaded error see this article.

Even though enhanced for loop internally uses an Iterator, it doesn't expose the reference to outside world.

Both while and for in combination with ListIterator and Iterator gives more flexibility and power as you can iterate both forward and backward, but yes for other Collection e.g. a Set or a Queue which doesn't support ListIterator, enhanced for loop is same as using Iterator with for or while loop.

here is a nice summary of why enhanced for loop was introduced in Java 5 and why you should use it, along with syntax and example of how to use it for iterating over collection and array.

How does Enhanced for loop works in Java?

That's all about how enhanced for loop works in Java. I am sure you have been using enhanced for loop frequently but you should know that you can use any object which implements Iterable here. Even your custom object can be used here if it implements java.util.Iterator interface. Enhanced for loop of JDK 5 is best for read-only iteration i.e. you just want to access, read or print data but it's not suitable if you want to remove elements during traversal, for that use Iterator with either for or while loop in Java. To learn more about enhanced for loop and other Java 5 features, read Core Java For Impatient.

No comments :

Post a Comment