CodeGym/Java Blog/Loops in Java/For-each loop in Java
Author
Artem Divertitto
Senior Android Developer at United Tech

For-each loop in Java

Published in the Loops in Java group
members

What's a for-each loop?

A for-each is a kind of for loop that you use when you need to process all the elements of an array or collection. That said, the phrase for-each is not actually used in this loop. Its syntax is as follows:
for (type itVar : array)
{
    // Operations
}
Where type is the type of the iterator variable (which matches the datatype of elements in the array!), itVar is its name, and array is an array (other data structures are also allowed, for example, some sort of collection, like ArrayList), i.e. the object on which the loop is executed. As you can see, this construct does not use a counter: the iterator variable simply iterates over the elements of the array or collection. When such a loop is executed, the iterator variable is sequentially assigned the value of each element of the array or collection, after which the specified block of statements (or statement) is executed.

In addition to the for-each loop, Java also has a forEach() method. You can read about it in the article entitled "Stop writing loops!" Top 10 best practices for working with collections in Java 8

Note: a for-each loop can be applied to arrays and any classes that implement the java.lang.Iterable interface. The following for loop would be equivalent to the code above:
for (int i=0; i < array.length; i++)
{

    // Statements
}

Example of a for-each loop

We create an array of student scores. Then we use a for-each loop to print out all the estimates, calculate the average score, and find the top score.
public class ForEachTest {

// A method that prints all scores
public static void printAllScores(int[] scores) {
        System.out.print("|");
        for (int num : scores) {

            System.out.print(num + "|");
        }
        System.out.println();
    }

// A method that displays the average score

public static double getAverageScore(int[] numbers) {
        int totalScore = 0;

        for (int num : numbers) {
            totalScore = num + totalScore;
        }
        return ((double) totalScore / numbers.length);

    }
// A method that determines the best (maximum) score
    public static int getBestScore(int[] numbers) {
        int maxScore = numbers[0];

        for (int num : numbers) {
            if (num > maxScore) {
                maxScore = num;
            }
        }
        return maxScore;
    }

public static void main(String[] args) {

// Array of scores
int[] scores = {5, 10, 7, 8, 9, 9, 10, 12};


  int bestScore = getBestScore(scores);
        System.out.print("All the scores: ");
        printAllScores(scores);
        System.out.println("The highest score is " + bestScore);
        System.out.println("The average score is " + getAverageScore(scores));
    }

}
Program output:
All the scores: |5|10|7|8|9|9|10|12|
The highest score is 12
The average score is 8.75
Now, let's see what a method for printing all the scores would look like if we used an ordinary for loop:
public static void printAllScores(int[] scores) {
        System.out.print("|");
        for (int i = 0; i < scores.length; i++) {

            System.out.print(scores[i] + "|");
        }
        System.out.println();
    }
If we call this method from the main method, then we get this result:
All the scores: |5|10|7|8|9|9|10|12|

Example of a for-each loop with collections

We create a collection of names and display all the names on the screen.
List<String> names = new ArrayList<>();
        names.add("Snoopy");
        names.add("Charlie");
        names.add("Linus");
        names.add("Shroeder");
        names.add("Woodstock");

        for(String name : names){
            System.out.println(name);
        }

Limitations of a for-each loop

The for-each loop's compact form is considered easier to read than a for loop, and it is considered best practice to use a for-each loop wherever possible. However, a for-each loop is a less universal construct than an ordinary for loop. Here are some simple cases where a for-each loop either won't work at all or will work, but only with difficulty.
  1. If you want to run through a loop from the end to the beginning. That is, there is no for-each loop that is a direct analogue to the following code:

    for (int i= array.length-1; i>0; i--)
    {
          System.out.println(array[i]);
    }
  2. For-each is not suitable if you want to make changes to an array. For example, you can't sort an array without changing the location of its elements. Additionally, in the following code, only the iterator variable will change, not the element of the array:

    for (int itVar : array)
    {
        itVar = itVar++;
    }
  3. If you are looking for an element in an array and you need to return (or pass on) the index of the element you are looking for, then it is better to use an ordinary for loop.

A helpful video about the for-each loop

Loops in the CodeGym course

On CodeGym, we start practicing using loops at Level 4 of the Java Syntax quest. Several of the lessons in that level, as well as many of the tasks in various levels, are devoted to loops in order to reinforce your skills in working with them. Basically, there's no way you can escape them — loops are one of the most important constructs in programming.

More information about for-each and other loops

  1. The while statement. The article is about to the simplest kind of loop: the while loop, which CodeGym uses to introduce loops to students.
  2. Stop writing loops! Top 10 best practices for working with collections in Java 8. This article will help CodeGym students who are at least halfway through the course learn many interesting things about working with collections.
Comments (4)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Antonio Lopez
Level 59
Expert
10 September 2023, 00:29
clarifying with such precision where to use for-each and where for, that is really teaching. Usually other courses only tell you, here's the syntax and do it as best you can, but in codegym they really teach you, by making you think about cases where the code breaks.
aijo
Level 30 , Germany, Germany
30 January 2022, 09:01
for (int i= array.length-1; i>0; i--)
{
      System.out.println(array[i]);
}
why don't we print the first element (index 0) here? look like a typo.
P.B.Kalyan Krishna
Level 24 , Guntur, India
29 March 2022, 09:08
Yes. It should be i >= 0;
Andrei
Level 41
4 November 2020, 07:53
The video doesn't work anymore. Other than that, great info!