
The for-each loop is used to access each successive value in a collection of values.
This foreach loop is commonly used to iterate over an array or a Collections class (eg, ArrayList).
For-Each loop Syntax is given below
//... Foreach loop over all elements in arr.Actual working mechanism using indexes in Java4 and equivalent to for loop.
for (type var : arr) {
Body-of-loop
}
//... For loop using index.In Collections we can use variable as an Object to iterate all elements in the object. Here we can work more progressively with collections. No need to use Iterator.
for (int i = 0; i < arr.length; i++) {
type var = arr[i];
Body-of-loop
}
//... Foreach loop over all elements in arr.Using iterator we can iterate the elements with specified methods and equivalent to for loop.
for (type var : coll) {
Body-of-loop
}
//... Loop using explicit iterator.Advantages of for-each Loop:
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
type var = iter.next();
Body-of-loop
}
- Less error prone code
- Improved readability
- Less number of variables to clean up
- Cannot be used where the collection is to be altered while traversing/looping through
- My not be suitable while looping through multiple collections in parallel
- Example program on for-each loop.