How do you execute a for-each loop in java?


The Java for-each loop is an enhanced form of the standard for loop. It was introduced in Java 5.

When to use:

The for-each loop can be used to iterate over all the elements of an array or the data stored using the classes of Java Collections framework e.g. ArrayList, vector, linkedlist, etc.

svg viewer


The generalized syntax of for-each loop is given below:

//for iterating over an array
for(datatypeOfArray var : arrayName){
  //Statements using the var
//for iterating over a Collection
for(datatypeOfCollection var : collectionName){
  //Statements using the var

The below illustration will help you understand it better.

svg viewer

There is no iterator i used in the for-each loop unlike the standard for loop.


Let’s print out the names of animals stored in an ArrayList using the for-each loop.

class ForEach {
  public static void main( String args[] ) {
    ArrayList<String> animals = new ArrayList<>();
    //Adding the names to the ArrayList

    //Printing out using for-each loop
    for(String var : animals)