When to Use Indexed vs Enhanced for Loops
You'll learn: How to choose between traditional indexed for loops and enhanced for-each loops when working with arrays.
The Core Trade-Off
Both loop styles let you visit every element in an array, but they're designed for different scenarios:
Use an indexed for loop when:
- You need to modify array elements (change their values)
- You need the index position (to compare neighbors, skip elements, or print positions)
- You're iterating backward or with custom step patterns
- You need to work with multiple arrays simultaneously
int[] scores = {85, 90, 78};
// Need index to modify elements
for (int i = 0; i < scores.length; i++) {
scores[i] += 5; // Boost all scores
}
Use an enhanced for-each loop when:
- You only need to read each element (no modifications)
- You don't care about the position
- You want cleaner, simpler code with no index management
int[] scores = {85, 90, 78};
// Just reading values
for (int score : scores) {
System.out.println(score);
}
Think of It This Way
An enhanced for loop is like walking through a museum exhibit—you see each piece in order but don't know the room numbers. An indexed loop is like having a map with numbered locations—you can jump around, revisit, or rearrange things.
Key Takeaway: Use enhanced for loops for simple read-only traversal; use indexed for loops when you need the position or must modify array elements.