JavaRush /Java Blog /Random EN /for-each loop in Java

for-each loop in Java

Published in the Random EN group

What is foreach in Java?

For-each is a type of for loop that is used when you need to process all the elements of an array or collection. “For each” is translated from English as “for everyone”. Actually, the phrase foreach itself is not used in this cycle. Its syntax is as follows:
for (type itVar : array)
{
    Блок операторов;
}
Where typeis the type of the iterative variable (the same as the data type in the array!), itVaris its name, arrayis the array (there may also be another data structure, some kind of collection, for example ArrayList), that is, the object on which the loop is executed. As you can see, a counter is not used in this design; the iteration variable iterates over the elements of an array or collection, and not the index values. When executing such a loop, the iteration 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.

Apart from the for-each loop, Java also has a forEach() method. You can read about it, for example, in the article “ Stop writing cycles!” Top 10 Best Methods for Working with Collections in Java 8

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

    Блок операторов;
}

Java foreach example

Let's create an array of student grades. Then, using for-each, we print out all the scores, display the average score, and find the maximum of them.
public class ForEachTest {

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

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

//method that displays the average score

public static double midGrade(int[] numbers) {
        int grade = 0;

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

    }
//method in which the best (maximum) score is calculated
    public static int bestGrade(int[] numbers) {
        int maxGrade = numbers[0];

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

public static void main(String[] args) {

//array of ratings
int[] grades = {5, 10, 7, 8, 9, 9, 10, 12};


  int highest_marks = bestGrade(grades);
        System.out.print("All the grades: ");
        printAllGrades(grades);
        System.out.println("The highest grade is " + highest_marks);
        System.out.println("The average grade is " + midGrade(grades));
    }

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

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

An example of using a for-each loop with collections

Let's 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 the for-each loop

The compact form of for-each is considered more readable than for, and it is considered good practice to use for-each where it can be done. However, for-each is a less versatile construct than regular for. Here are a few simple cases where using for-each will not work at all or will work, but with difficulty.
  1. If you want to go through a loop from end to beginning. That is, there is no direct for-each 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, it will not be possible to sort an array without swapping its elements. Or, in the following code, it is not the array element that will change, but only the iteration variable:

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

Useful video about for-each prepared by a JavaRush student

Loops in the JavaRush course

At JavaRush, we start using loops in practice at level 4 of the Java Syntax quest . There are several lectures devoted to them, as well as many tasks of different levels to strengthen the skills of working with them. In general, you can’t escape them; loops are one of the most important constructs in programming.

More about for-each and loops:

  1. For and For-Each Loop: the tale of how I iterated, iterated, but did not iterate - a good detailed article about for and for-each loops in Java. Designed for a trained reader (approximately JavaRush level 10 and above).
  2. While statement . The article is devoted to the simplest cycle while, with which you begin to get acquainted with cycles in JavaRush.
  3. Stop writing cycles! Top 10 best methods for working with collections in Java 8 . From this article, a JavaRush student who has already completed half the course or more will learn a lot about working with collections.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION