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

Syntax

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.

Example

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
animals.add("Dog");
animals.add("Cat");
animals.add("Sheep");
animals.add("goat");
//Printing out using for-each loop
for(String var : animals)
{
System.out.println(var);
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved