How does Java for-each loop works?

Loops in programming languages used to iterate over collections like for loop, while .. do etc. In Java iterating over collections looks very ugly. Consider method in the following example which uses for loop to iterate over a collection.

public static void main(String[] args) {
	List fruitList = new ArrayList();
	fruitList.add("mango");
	fruitList.add("banana");
	fruitList.add("apple");
	printFruits(fruitList);
}

static void printFruits(List fruits) {
	for (Iterator fruit = fruits.iterator(); fruit.hasNext();)
		System.out.println(fruit);
}

The iterator is just clutter and it has many opportunities for error. The iterator variable occurs three times in each loop, that is two chances to get it wrong.

To avoid this we use the for-each construct of Java. Which looks clean and very fewer chances of error while it works just like the above methods. for-each loop example below:

static void printFruits(List fruits) {
	for (String fruit : fruits) {
		System.out.println(fruit);
	}
}

In for-each : mean ‘in’. In the above example, an element of a collection will come in fruit variable. This is very simple and the compiler will automatically declare Iterator and other things for you.

Additionally, this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface.

For more details check Oracle Java Documentation foreach loop

for-each vs forĀ  Basic Differences

The only practical difference between for and foreach is that, in the case of indexable objects, you do not have access to the for the loop. An example when the basic for loop is required:

for(int x = 0; x < array.length; x++) {
   if(x < 5) {
      // Do something special
   }  else {
      // Do other stuff
   }
}

Although you could manually create a separate index int-variable with foreach,

int idx = -1;
for(int i : intArray) {
   //Do something
   idx++;
   ...
}

foreach vs for Performance

When accessing collections, a foreach loop is significantly faster than the for loop array access. When accessing arrays, at least with primitive and wrapper arrays access via indexes is dramatically faster.

Indexes access of arrays are 23-40 percent faster than iterators when accessing int or Integer arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.