Iterating Arrays with Enhanced for Loops
What You'll Learn
You'll learn how to use the enhanced for loop (for-each) to cleanly traverse every element in an array without managing index variables.
The Core Idea
The enhanced for loop shines when working with arrays. Instead of manually tracking indices and using bracket notation to access elements, the for-each loop automatically retrieves each element for you, one at a time, from start to finish.
Think of it like this: Imagine you have a basket of apples (an array). The traditional for loop is like numbering each apple and pulling them out by number. The enhanced for loop is like reaching in and grabbing each apple in order without caring about its position number—you just want to inspect or use each apple.
Syntax with Arrays
int[] scores = {85, 92, 78, 90, 88};
for (int score : scores) {
System.out.println("Score: " + score);
}
This reads as: "For each int called score in the scores array, do this..."
The loop automatically:
- Starts at index 0
- Visits every element in order
- Stops after the last element
- Assigns each element to your loop variable (
score)
Why Use It with Arrays?
- Cleaner code: No index variable cluttering your logic
- Fewer errors: Can't accidentally use the wrong index or go out of bounds
- Intent is clear: Signals you want to process all elements sequentially
Remember: You still can't modify the array's elements through the loop variable or access their index positions—but for simple traversal, this syntax is unbeatable.
Key Takeaway: Enhanced for loops provide the cleanest way to iterate through every element of an array when you don't need index information or element modification.