Java For-Each Loop
Syntax, Flow & Examples
When you're working with arrays or collections in Java, there comes a point where you just want to go through every element—no counters, no fuss. That's where the for-each
loop shines. It's Java's way of saying: "Let me handle the iteration, you focus on what needs to be done."
What Is a For-Each Loop?
The for-each loop—also known as the enhanced for loop—is a control flow statement introduced in Java 5. It’s designed to iterate over elements in arrays and collections without the need for an index variable.
Syntax of For-Each Loop
for (datatype element : collection) {
// use element
}
Here’s what each part means:
datatype
: the type of the elements (e.g.,int
,String
)element
: a temporary variable representing the current item in the loopcollection
: an array or iterable collection
Example: Iterating Over an Array
public class ForEachArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println("Value: " + number);
}
}
}
Value: 10
Value: 20
Value: 30
Value: 40
Value: 50
Why Use For-Each Instead of Traditional For Loop?
Here’s a side-by-side thought:
- With a traditional loop: you control every step of iteration.
- With a for-each loop: Java handles the loop mechanics for you.
It’s clean, readable, and removes the risk of off-by-one errors.
For-Each with Strings
public class ForEachString {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}
Fruit: Apple
Fruit: Banana
Fruit: Cherry
For-Each with Collections (ArrayList)
import java.util.ArrayList;
public class ForEachCollection {
public static void main(String[] args) {
ArrayList colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
for (String color : colors) {
System.out.println("Color: " + color);
}
}
}
Color: Red
Color: Green
Color: Blue
Can I Modify Elements Inside a For-Each Loop?
Good question—and here's a warning. You can’t change the original array or collection items directly inside a for-each loop, at least not for primitives or immutable objects.
int[] values = {1, 2, 3};
for (int value : values) {
value = value * 2; // This doesn't change the array!
}
// values remain {1, 2, 3}
Why? Because value
is a copy of each item, not a direct reference.
For-Each with Nested Arrays (2D Arrays)
public class ForEach2DArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
1 2
3 4
5 6
Limitations of For-Each Loop
While for-each makes code cleaner, it does come with limitations:
- You can’t get the index of the current element.
- You can’t remove items from a collection safely (unless using an
Iterator
). - Direct element modification (like updating an array value) is not possible for primitive arrays.
When Should You Use For-Each?
Use it when:
- You need to access every element one by one
- You don’t care about the index
- Your code needs to be clean, readable, and minimal
Conclusion
The for-each loop is your go-to tool for readable, streamlined iteration. It removes distractions so you can focus on what matters: processing data. Whether you're looping over fruit names, colors, or 2D matrices, for-each keeps your intent clear and your code crisp.
QUIZ
Question 1:What is the correct syntax of a Java for-each loop?
Question 2:You can modify the original values of a primitive array inside a Java for-each loop.
Question 3:Which of the following is a valid use-case for a for-each loop?
Question 4:Which of the following are limitations of the for-each loop in Java?
Question 5:What will be the output of the following code?
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}