AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Java for-each loop: tutorial

PARTAGEZ

The for-each loop in Java allows you to execute arrays or collections faster and safer, avoid errors and improve code readability. In this tutorial, we explain in detail the structure and advantages of the for-each method and show you how to use the loop in your code.

What is the Java for-each loop used for?

The for-each loop is used in many scenarios where developers need to work with arrays. A common application is for example displaying or searching for specific elements in an array. The for-each loop can also be used to execute elements in an applied list like an ArrayList. At each iteration, you can make automatic manipulations using common Java operators, without having to write a separate statement for each element.

If we compare the for-each method in Java with the for loop method in Java, with the for-each loop, it there is no need to take into account the position or size of the array. This helps prevent a position from falling outside the applicable range. The for-each loop internally uses an iterator to call each element of the array or list one after the other. The iterator automatically counts into the array or list and ends the loop when all elements have been executed.

However, if you need to navigate to position, for example to process the next or previous element, it is potentially better to resort to for loop or to the while loop.

Java for-each loop syntax

The basic syntax of a for-each loop in Java looks like this:

for (type item : array | collection) {
// bloc de code
}

Java

  • “array/collection”: name of the array or collection
  • “item”: each element of the array or collection is assigned to this variable.
  • “type”: data type of the array or collection

Within the loop, the code block is executed for each iteration.

Examples of using the Java for-each loop

Below we explain the use of the for-each method using the on-screen displays and arithmetic operations.

Show items on screen

Using the for-each loop, you can display on screen each element of an array or collection.

class Main {
  public static void main(String[] args) {

    // array
    String[] names = {"Sophie", "Tim", "Anna", "John", "Melissa"};

    // pour chaque boucle
    for (String name: names) {
      System.out.println(name);
    }
  }
}

Java

The result displayed on the screen is as follows:

Sophie
Tim
Anna
John
Melissa

Java

In the same way, it is possible to present the elements of a list. The source code of the loop does not change.

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // liste
    ArrayList<String> names = new ArrayList<String>();

    names.add( "Sophie" );
    names.add( "Tim" );
    names.add( "Anna" );
    names.add( "John" );
    names.add( "Melissa" );

    // pour chaque boucle
    for(String name: names){
      System.out.println(name);
    }
  }
}

Java

A string is generated for each name in the list:

Sophie
Tim
Anna
John
Melissa

Java

Calculate the sum of the elements of an array or collection

Thanks to the for-each method in Java, it is quick and easy to perform arithmetic operations, such as adding elements of an array or a list. In the code block, operators are associated with variables serving as wildcards for each element.

class Main {
  public static void main(String[] args) {

    // array
    int[] numbers = {10, 34, 7, 19, -28};
    int sum = 0;

    // addition
    for (int number: numbers) {
      sum += number;
    }

    System.out.println("Result = " + sum);
  }
}

Java

The numbers in the array are added in turn to the “sum” variables which have been previously declared outside the loop. The result is as follows:

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact