← Back to Core Java Course | Chapter 4: Control Flow | Lesson 8 of 9

Java For-Each Loop

The for-each loop iterates over every element of an array or collection in sequence, using simpler syntax than a traditional indexed for loop when the current index isn't needed.
Syntax
java
for (dataType item : collection) {
    // use item
}

Basic For-Each Syntax

The for-each loop, also called the enhanced for loop, iterates over every element of an array or collection in sequence using the syntax for (type variable : source), without requiring a counter variable or explicit length check.

Example: Basic For-Each Syntax

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare numbers and set it to {1, 2, 3}
		int[] numbers = {1, 2, 3};
		for (int n : numbers) {
			// Print a line to the console
			System.out.println(n);
		}
	}
}

For-Each over Arrays

For-each works with arrays of any type, including primitives like int, double, and char, reading each element in the array's natural order from the first index to the last without any manual indexing.

Example: For-Each over Arrays

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare prices and set it to {9.99, 4.50, 12.25}
		double[] prices = {9.99, 4.50, 12.25};
		for (double price : prices) {
			// Print a line to the console
			System.out.println(price);
		}
	}
}

For-Each over Collections

For-each also works on any Java collection that implements Iterable, such as ArrayList, HashSet, or a Map's entrySet, making it a consistent way to loop over both arrays and collection types with the same syntax.

Example: For-Each over Collections

java
// Import java.util.ArrayList so it can be used by its short name
import java.util.ArrayList;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new ArrayList object and store it in names
		ArrayList<String> names = new ArrayList<>();
		names.add("Alice");
		names.add("Bob");
		for (String name : names) {
			// Print a line to the console
			System.out.println(name);
		}
	}
}

For-Each with 2D Arrays

Iterating a multi-dimensional array with for-each requires nesting two loops: the outer loop retrieves each row as a smaller array, and the inner loop then iterates over the individual values within that row.

Example: For-Each with 2D Arrays

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		int[][] grid = {{1, 2}, {3, 4}};
		for (int[] row : grid) {
			for (int value : row) {
				// Print to the console without a newline
				System.out.print(value + " ");
			}
		}
	}
}

Limitations of For-Each

For-each cannot access or modify the current index, cannot remove elements from the collection safely during iteration, and reassigning the loop variable itself has no effect on the underlying array or collection.

Example: Limitations of For-Each

java
public class Main {
	public static void main(String[] args) {
		int[] numbers = {1, 2, 3};
		for (int n : numbers) {
			n = 99; // reassigning n has no effect on numbers[]
		}
		System.out.println(numbers[0]);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to modify the collection while using for-each, which throws ConcurrentModificationException.
  2. Expecting assigning to the loop variable to change the array element, when it only changes a copy for primitives.
  3. Using for-each when you need the index, which it does not give.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.