For-Each Loop in Java (Simplest Way to Loop Through Arrays)
β What is a For-Each Loop?
The for-each loop (also called the enhanced for loop) in Java is a special type of loop used to iterate over arrays and collections. It is simpler and more readable than the traditional for
loop when you only need to access each element and do not need the index.
This loop is ideal when you’re working with arrays, ArrayList
, or other collections, and you just want to perform an action on each item.
π§ Syntax of the For-Each Loop
-
dataType
: The type of elements in the array or collection. -
variable
: A temporary variable that holds each element. -
arrayOrCollection
: The array or collection you’re looping through.
π― Example 1: For-Each Loop with an Integer Array
Output:
π― Example 2: For-Each Loop with a String Array
Output:
π« Limitations of For-Each Loop
-
You cannot modify elements directly using the for-each loop (you donβt have access to the index).
-
Not suitable when you need to skip, reverse, or partially loop through data.
-
Not ideal when working with multi-dimensional arrays if you need precise control.
β When to Use For-Each Loop
-
You just want to read or print all items in an array or collection.
-
You donβt care about the index position of each element.
-
You want cleaner and more readable code.
π For vs For-Each: Quick Comparison
Feature | For Loop | For-Each Loop |
---|---|---|
Access by index | β Yes | β No |
Suitable for updates | β Yes | β No (read-only) |
Readability | β Less readable | β More readable |
Use case | General looping | Reading items only |
The for-each loop is one of the most elegant ways to read elements in Java. Use it when you need simplicity and readability, especially for tasks like printing arrays or looping through lists.