← Back to Week 2 Hub

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

for (int i = 0; i < colors.length; i++) { System.out.println(colors[i]); }
 

Console Output

for-each Loop

for (String color : colors) { System.out.println(color); }
 

Console Output

Syntax Breakdown

Read it as: "for each String color in colors" — hover over each part to see what it does.

for ( String color : colors )

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.

"Print every element in the array"

Click to reveal

for-each

You only need the values, not the index. for-each is simpler and cleaner.

"Print each element with its position number"

Click to reveal

for

You need the index i to show the position. for-each doesn't give you an index.

"Double every value in the array"

Click to reveal

for

You need to write back to array[i]. for-each gives you a copy, not a reference to the slot.

Tip: When in doubt, start with 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.

← Arrays: Memory & Indexing Array Operations →