for-each Loop vs for Loop
Two ways to loop through arrays — when to use which
Step-Through Comparison
Both loops process the same array: String[] colors = {"Red", "Blue", "Green", "Yellow", "Purple"}
Traditional for Loop
Console Output
for-each Loop
Console Output
Syntax Breakdown
Read it as: "for each String color in colors" — hover over each part to see what it does.
When to Use Which
| Need | for |
for-each |
|---|---|---|
| Access elements by value | ✓ Yes | ✓ Yes |
| Know the index | ✓ Yes | ✗ No |
| Modify elements in the array | ✓ Yes | ✗ No (read-only) |
| Loop backwards | ✓ Yes | ✗ No |
| Simpler syntax | ✗ No | ✓ Yes |
Which Loop Would You Use?
Click each scenario to reveal the best choice.
Click to reveal
for-each
You only need the values, not the index. for-each is simpler and cleaner.
Click to reveal
for
You need the index i to show the position. for-each doesn't give you an index.
Click to reveal
for
You need to write back to array[i]. for-each gives you a copy, not a reference to the slot.
for-each. Switch to for if you need the index or need to modify the array.
Step through both loops side by side to see how they access the same array differently.