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

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
public class Main {
	public static void main(String[] args) {
		int[] numbers = {1, 2, 3};
		for (int n : numbers) {
			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
public class Main {
	public static void main(String[] args) {
		double[] prices = {9.99, 4.50, 12.25};
		for (double price : prices) {
			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;
public class Main {
	public static void main(String[] args) {
		ArrayList<String> names = new ArrayList<>();
		names.add("Alice");
		names.add("Bob");
		for (String name : names) {
			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
public class Main {
	public static void main(String[] args) {
		int[][] grid = {{1, 2}, {3, 4}};
		for (int[] row : grid) {
			for (int value : row) {
				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]);
	}
}

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.