Trusted answers to developer questions

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

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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);
}
}
}

RELATED TAGS

java
loops
foreach
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?