For-Each Loops
in Java
Master the enhanced for loop to iterate over arrays and collections with cleaner, safer code.
What Is a For-Each Loop?
A for-each loop (also called an enhanced for loop) is a simplified way to iterate through every element in an array or collection. Instead of managing an index variable, the loop automatically hands you each element, one at a time.
How the Loop Traverses an Array
On each iteration, the loop copies the next element from the array into the loop variable. No index needed: Java handles the traversal automatically.
Why Use a For-Each Loop?
.length.ArrayIndexOutOfBoundsException.ArrayList, HashSet, and any Iterable.The Syntax
int, String).Iterable being traversed.Anatomy of a For-Each Statement
Traditional For vs For-Each
When Not to Use For-Each
The for-each loop is read-only over the collection. Use a traditional for loop when you need to:
i.How to Write a For-Each Loop
ArrayList are you iterating over?int, String, double, an object?)name for a String[] of names).[i] needed.Example: Summing an Array
Example: Searching for a Value
Example: Iterating an ArrayList
The Read-Only Trap
For-Each with 2D Arrays
Common Mistakes
int when iterating a String[]. The loop variable type must match the element type.arr[val] inside the loop. The variable already is the element, not an index.Comparison Summary
| Traditional For | For-Each | |
|---|---|---|
| Syntax complexity | 3 parts (init, condition, update) | 1 declaration + collection |
| Index access | ✓ Yes | ✕ No |
| Modify elements | ✓ Yes | ✕ No (primitives) |
| Reverse traversal | ✓ Yes | ✕ No |
| Risk of off-by-one | High | None |
| Works with ArrayList | ✓ Yes | ✓ Yes |
| Best for | Full control over iteration | Simple read-only traversal |
Question 1 of 5
What is the output of the following code?
Question 2 of 5
Which of the following is a limitation of the for-each loop?
Question 3 of 5
What should replace ??? to correctly iterate over a String[] array called names?
String elements, the correct form is String name : names.Question 4 of 5
What is the output of this code?
v inside a for-each loop changes only the local copy, not the original array. vals[0] remains 10.Question 5 of 5
To iterate over a 2D int array called grid, what type should the outer loop variable be?
int[] (a 1D array).