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:

Apple
Banana
Orange

 Example 2: Iterating Over Numbers


 


 Example 3: Sum of Array Elements


 

📌 Output:

Sum = 15

 Example 4: Iterating Over a Collection (ArrayList)


 

📌 Output:

BMW
Audi
Tesla

 Advantages of For-Each Loop

  1. Readable – no need to manage index variables

  2. Safe – avoids out-of-bounds errors

  3. 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 for loop if needed)

You may also like...