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 |
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.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]); }
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++; }
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 courseOn 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
- The while statement. The article is about to the simplest kind of loop: the
while
loop, which CodeGym uses to introduce loops to students. - 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.
GO TO FULL VERSION