Xenofon Dimitroulis

About 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.

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

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close