Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
loops
foreach

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

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring