For Each Loop
For Each Loop
A school program needs reliable data and clear rules. An enhanced for loop visits each element of an array or iterable. It is useful when a marks report needs each value without its position.
Understand
An enhanced for loop visits each element of an array or iterable.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Assigning to the loop variable does not replace a primitive element in the array. Use an indexed loop when positions or replacement are needed.
For Each Loop
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<String> 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.
Important boundaries and mistakes
Assigning to the loop variable does not replace a primitive element in the array. Use an indexed loop when positions or replacement are needed.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Assigning to the loop variable does not replace a primitive element in the array.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
int[] marks = {
70, 80
}
;
for (int mark : marks) {
System.out.println(mark);
}
}
}
Now change one thing: Add 90 to the marks array. Predict the new behavior before checking the worked variation.
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
int[] marks = {
70, 80
}
;
for (int mark : marks) {
System.out.println(mark);
}
}
}
Expected output
70
80An enhanced for loop visits each element of an array or iterable. It is useful when a marks report needs each value without its position.
Assigning to the loop variable does not replace a primitive element in the array. Use an indexed loop when positions or replacement are needed.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Worked variation: Add 90 to the marks array. The enhanced for loop visits it after 70 and 80.
Check your understanding
Check a common mistake
What to remember
An enhanced for loop visits each element of an array or iterable. It is useful when a marks report needs each value without its position. Assigning to the loop variable does not replace a primitive element in the array. Use an indexed loop when positions or replacement are needed.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.