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:

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) {

		// 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) {

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


Example 1
Example 2
Example 3

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.

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();


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

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

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

	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) {



Download Source Code

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

Download the Eclipse project of this example:

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


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.
Notify of

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

Inline Feedbacks
View all comments
Back to top button