Java For-Each Loop
Java For-Each Loop (Enhanced for Loop)
The for-each loop is used to iterate over arrays or collections in a simpler and more readable way than a traditional for loop.
It eliminates the need for an index variable.
Syntax
-
item→ current element of the array/collection -
arrayOrCollection→ the array or collection being iterated
Example 1: Iterating Over an Array
📌 Output:
Example 2: Iterating Over Numbers
Example 3: Sum of Array Elements
📌 Output:
Example 4: Iterating Over a Collection (ArrayList)
📌 Output:
Advantages of For-Each Loop
-
Readable – no need to manage index variables
-
Safe – avoids out-of-bounds errors
-
Quick – easier to iterate over arrays and collections
Limitations
-
Cannot modify the elements of the array/collection directly
-
Cannot get the index of the element (use traditional
forloop if needed)
