The Enhanced for Loop (for-each): Syntax and Purpose
What you'll learn: How to iterate through collections of data more simply, without managing index variables.
The Problem with Traditional Loops
When you use a traditional for loop to go through an array, you have to manually manage an index variable, check the array's length, and use bracket notation to access elements. That's a lot of bookkeeping when all you really want is to look at each item one by one.
The Enhanced for Loop Solution
Java provides a simplified syntax called the enhanced for loop (also known as for-each) that lets you iterate over every element in an array without touching indices at all.
Basic Syntax
for (dataType variable : array) {
// use variable here
}
Think of the colon (:) as meaning "in" — you're saying "for each element in this collection."
Concrete Example
Traditional loop:
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
int num = numbers[i];
System.out.println(num);
}
Enhanced for loop:
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
The enhanced version automatically gives you each element directly—no index, no bounds checking, no array[i] notation needed.
When to Use It
Use the enhanced for loop when you need every element and don't care about positions or indices. If you need to know which position you're at, or need to skip elements, stick with the traditional for loop.
Key Takeaway: The enhanced for loop simplifies iteration by giving you each element directly, eliminating index management—use it when you just need to process every item in order.