Course contentsShow
← Java
Lesson 248 of 2,8706. ArraysFree lesson

Enhanced for Loop (for-each) with Arrays

Learn the simplified for-each syntax for reading array elements without explicit indexing.

Enhanced for Loop (for-each) with Arrays

You'll learn how to use the for-each loop to read through array elements without manually managing index numbers.

What is the Enhanced for Loop with Arrays?

You've already seen the enhanced for loop syntax in general. Now let's see it in action specifically with arrays. The for-each loop provides a cleaner, simpler way to read every element from an array when you don't need to know or use the index position.

Instead of writing a traditional for loop with initialization, condition, and increment, you simply declare a variable that will hold each array element as you loop through.

Syntax Reminder

for (elementType variable : arrayName) {
    // use variable here
}

Example with Arrays

int[] scores = {85, 92, 78, 95, 88};

// Enhanced for loop - clean and simple
for (int score : scores) {
    System.out.println("Score: " + score);
}

// Compare to traditional for loop
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score: " + scores[i]);
}

Both loops produce identical output, but the for-each version is more readable when you just need to access each value.

Think of It This Way

The for-each loop is like someone handing you each item from a box, one at a time. You don't need to know which slot it came from—you just receive each item and do something with it. The traditional for loop is like reaching into numbered slots yourself.

Key Takeaway: The enhanced for loop simplifies reading array elements by automatically iterating through each one without requiring explicit index management—perfect when you only need the values, not their positions.