Java Foreach Loop



Java foreach is used to iterate series of values or objects. Foreach loop allows for the access of each successive object in a collection of objects. Java foreach is commonly used to iterate over array, arraylist or collection. It also iterates over anything that implements the Iterable interface (must define iterator() method).

Java Foreach example 1

for (type var : arr) {
    code to be executed in the foreach loop.
}

Java Foreach example 2

for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    code to be executed in the foreach loop.
}

Java Foreach Example 3:

int[] ar = {1, 2, 3};
int sum = 0;
for (int d : ar) { 
    System.out.println("value of current element "+d);
}

Java Iterator based foreach loop

for (Iterator<type> iter = ar.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    code to be executed in the foreach loop.
}