Java For-Each Loop
In this page:
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
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
for (int n : numbers) {
System.out.println(n);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 + " ");
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: