Java for each loop (enhanced for loop) Tutorial

In this section we will learn what the for each loop is and how to use it in Java.

What is for-each loop in Java?

When we have a list of elements (like an array) or basically an iterable object and want to run a block of code for each element of that list, we can use the for-each loop.

Java for-each Loop Syntax

Here’s the structure of the for each loop:

for (type variableName : iterableList) {
// code block to be executed
}
`for` keyword: to create a `for each` loop, we start with the keyword `for`.

(): inside the parentheses that comes after the keyword for we set the name of the list (that contains the elements) and a variable of the same type that will receive each value of the list and this variable and its value can be used in the body of the for loop.

`iterableList`: this is the list that contains the elements.
`varaibleName`: This is the variable that each element of the list will be stored in it.

:: we use colon : to separate iterableList from variableName.

`{}`: the pair of braces that comes after the parentheses, declares the body of the loop.

Example: using for-each loop to iterate an array

public class Simple {
public static void main(String[] args) {
int iArray[]= {1,2,3,4,5,56,6,7,23,423,42,34,23,423,42,3};
for(int i: iArray){
System.out.print(i+", ");
}
}
} Output: 1,2,3,4,5,56,6,7,23,423,42,34,23,423,42,3

How does for-each loop work?

Here we used an array variable that is named iArray. In the array section you’ll learn more about this type of variables but in short, it’s a type of variable that allows developers to store multiple values instead of only one.

So here via the for-each loop, we looped through the elements of this list and sent its values to the output stream (console in this case).

Example: using nested for-each loop in Java

class Main{
public static void main(String[] args) {
int [][] multi = {
{1,2,3,4,5},
{6,7,8,9,10}
};
for (int []array : multi){
for (int b: array){
System.out.print(b);
}
}
}
}
Output:
12345678910

for loop Vs for-each loop

The main difference between the for loop and the for-each loop is that the for loop is design in a way so that we can easily loop through a specific number of an iterable object (like an array) while the for-each loop is designed in order to easily loop through the entire elements of an iterable object and not just a specific number of its element (although possible but this was not in its design purpose).