Java Foreach Loop

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


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.
}





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.