Java For-Each Loop
In this page:
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
// 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);
}
}
}
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
// 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);
}
}
}
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 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);
}
}
}
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
// 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 + " ");
}
}
}
}
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
- Trying to modify the collection while using for-each, which throws
ConcurrentModificationException. - Expecting assigning to the loop variable to change the array element, when it only changes a copy for primitives.
- Using for-each when you need the index, which it does not give.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: