Skip to content

For-Each Loops

  • Lesson
  • 1 min read
  • 3 of 3 in this chapter

A what loop?

We've talked about for loops and while loops, but there's one loop we haven't talked about: for-each loops.

For-Each Loops are exclusively for arrays, allowing us to go through each item. We can write them like this:

Java
int[] grades = {100,92,97,96,85};

for(int grade: grades) {
System.out.println(grade);
}

This does the same thing as the for loop in the previous chapter.

To write a for-each loop, we start with a for, and then in our () is where things change.

We first set the data type and a local variable name for each iteration.

In the first iteration of our loop, grade = grades[0]. In the second iteration, grade = grades[1].

Then, we add a :, and then specify the array. It's much easier than creating a for loop every time we iterate through an array.