What is foreach in Java?
For-each is a type of for loop that is used when all the elements of an array or collection need to be processed. “For each” is translated from English as “for everyone”. Actually, the foreach phrase itself is not used in this loop. Its syntax is the following:for (type itVar : array)
{
Блок операторов;
}
Where type
is the type of the iteration variable (coincides with the data type in the array!), itVar
is its name, array
is an array (there may also be another data structure, some kind of collection, for example, ArrayList
), that is, the object on which the loop is performed. As you can see, the counter is not used in this construction, the iteration variable iterates over the elements of the 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.
In addition to the for-each loop, Java also has the forEach() method. You can read about it, for example, in the article “ Stop writing cycles! Top 10 Best Practices for Working with Collections in Java 8 ” |
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 ratings would look like, performed using a normal 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 method main
, we 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);
}
for-each loop limits
The compact form of for-each is considered more readable than for, and it's good practice to use for-each where it can be done. However, for-each is less versatile than the regular for. Here are some simple cases where using for-each will not work at all or it will work, but with difficulty.-
If you want to loop through from the end to the 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]); }
-
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, not the array element will change, but only the iteration variable:
for (int itVar : array) { itVar = itVar++; }
-
If you're looking for an element in an array and need to return (or pass on) the index of the element you're looking for, it's better to use a regular for loop.
Useful for-each video by a CodeGym student
Loops in CodeGym courseOn CodeGym, the use of loops in practice is started at level 4 of the Java Syntax quest . There are several lectures devoted to them, as well as many tasks of different levels to consolidate the skills of working with them. In general, you can’t get away from them anywhere, cycles are one of the most important constructs in programming. |
More about for-each and loops:
- For and For-Each Loop: A Tale of How I Iterated, Iterated, But Not Iterated - A good detailed article on for and for-each loops in Java. Designed for advanced readers (approximately CodeGym level 10 and up).
- while statement . The article is devoted to the simplest cycle
while
, from which acquaintance with cycles in CodeGym begins. - Stop writing cycles! Top 10 Best Practices for Working with Collections in Java 8 . From this article, a CodeGym student who has already completed half of the course or more will learn a lot of interesting things about working with collections.
GO TO FULL VERSION