Core Java

Java for-each Loop Example

In this example we shall show you how to use the for-each loop.
This new way of iteration was introduced in Java 5 and offers a more convenient way of iterating over arrays and collections. It is an extension to the classic for loop and it is widly known as “enhanced for” or “for-each”. The phrase “for-in loop” is also used, but less often.

The main difference between the classic for loop and the new loop is the fact that it hides the iteration variable. As a result, usage of the for-each loop leads to a more readable code with one less variable to consider each time we want to create a loop thus the possibility of ending up with a logic error is smaller.

However, hiding the iterator has some drawbacks as well. For instance, we cannot use it to remove or replace items in a list and iteration over multiple collections in parallel is not possible. This means that it cannot replace the classic for loop everywhere. We can use it whenever access to only a single element in each iteration is needed.

We can use it over both arrays and collections, as well as over any class that implements the interface Iterable.

1. Syntax

The syntax of this new loop is very simple since it hides the iterator.

  • To iterate over the containts of an array: for (type variable: Array){}
  • To iterave over the elements of a colletion: for (type variable: Collection){}

2. Example 1

The following example demonstrates the use of for-each loop in different occasions:

foreachExample.java:

package com.javacodegeeks.core.for_each;

import java.util.ArrayList;
import java.util.List;

public class foreachExample {
	public static void main(String Args[]) {

		// Example 1
		System.out.println("Example 1");
		// Using for-each over a single dimension Array
		int myArray[] = { 1, 2, 3, 4, 5 };
		for (int var : myArray) {
			System.out.println(var);
		}

		// Example 2
		System.out.println("Example 2");
		// Using for-each over a two dimensions Array
		// we create an Array and initialize it using the classic for loop
		int myArray2[][] = new int[2][2];
		for (int i = 0; i < 2; i++) {
			for (int j = 0; j < 2; j++) {
				myArray2[i][j] = i + j;
			}
		}
		// we print all its values using the for-each loop
		for (int[] x : myArray2) {
			for (int y : x) {
				System.out.println(y);
			}
		}

		// Example 3
		System.out.println("Example 3");
		// Using for-each over a Collection
		// We create and initialize our list
		List myArrayList = new ArrayList();
		myArrayList.add("A");
		myArrayList.add("B");
		myArrayList.add("C");
		// we print all its values using the for-each loop
		for (String str : myArrayList)
			System.out.println(str);
	}
}

Output:

Example 1
1
2
3
4
5
Example 2
0
1
1
2
Example 3
A
B
C

3. Example 2

The following example demonstrates how to use for-each example in your own class. As mentioned above, all we have to do to is implement the interface Iterable in our class. The following class ClassRoom implements the interface, so we can use the for-each loop to iterate over the students names that are inside each room.

ClassRoom.java:

package com.javacodegeeks.core.for_each;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class ClassRoom implements Iterable, Iterator {

	ArrayList students;
	int count = 0;

	public ClassRoom() {
		// We initialize our ClassRoom with a few random Students
		students = new ArrayList();
		students.add("Tom");
		students.add("Mike");
		students.add("John");
		students.add("John");
		students.add("Bill");

	}

	@Override
	public Iterator iterator() {
		count = 0;
		return this;
	}

	@Override
	public boolean hasNext() {
		if (count < students.size()) {
			return true;
		}
		return false;
	}

	@Override
	public String next() {
		if (count == students.size())
			throw new NoSuchElementException();
		return students.get(count++);
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
	}

	public static void main(String Args[]) {
		// we create our ClassRoom's instance
		ClassRoom room_A = new ClassRoom();

		// We use for-each loop to print all students names in the classroom
		for (String str : room_A) {
			System.out.println(str);
		}
	}
}

Output:

Tom
Mike
John
John
Bill

Download Source Code

This was an example of using for-each loop in Java.

Download the Eclipse project of this example: ForEachExample.zip

Xenofon Dimitroulis

Xenofon has graduated from the Department of Informatics at Athens University of Economic and Business. His studies were focused in the area of Information Management, as well as Computer Systems and Networks. He has successfully developed a series of projects varying form simple desktop, web and mobile applications, scaling to more complex which included AI algorithm implementations and Multithreaded Distributed Systems.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button