Friday, July 21, 2023

How foreach or Enhanced for loop works in Java? Example

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 the basics of enhanced for loop, also known as for each loop in Java. The enhanced loop provides the cleanest way to loop through an array or collection in Java, as you don't need to keep track of the 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 a couple of important points related to it.

Btw, Java 5 introduced several useful features along with enhanced for loop like 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.
.


How enhanced for loop foreach works in Java? Example

Suppose, you want to loop over a List in Java, you can write the 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){
   System.out.println(city);
}

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 = i.next();
   System.out.println(city);
}

Of course, the 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 the outside world.

Both while and for in combination with ListIterator and Iterator give 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 examples 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. 



2 comments:

  1. Javin, thanks for the explanation. However, can you elaborate the point in the summary about Iterator being error prone? Do you mean the syntax is difficult? Or something else?

    ReplyDelete
  2. Does Enhanced for loop iterator under the hood. So if it does then how does the enhanced for loop works on simple java arrays.

    ReplyDelete