For-each loop in Java: iterate the elements of an array


Keywords: for-each loop, enhanced for loop, array, for loop

Learn Java programming Code Knowledge

This article will look at the so-called for-each loop, also known as enhanced for loop, in Java that is a tool for looping through all the elements in an array.

What is for-each loop in Java?

For-each loop, also known as enhanced for loop, is a way to efficiently and swiftly process all elements of an array. As the name suggests, it has similar properties to the “standard” for loop that we saw in the chapter on loops. The difference between the for-each loop and the for loop is that a for-each loop operates on each element, instead of a specific number of times.

How to create for-each loop in Java?

To create a for-each loop, we use a similar syntax as we use with the for loop.

  • First, we use the reserved word for followed by parentheses ( ).
  • Inside the parentheses, we specify the data type of the array we are working with, followed by a variable name. This variable is only defined inside the loop.
  • Finally, you enter a colon, :, followed by the array you want to iterate through.

Inside the curly brackets, we then write the operations we want to perform. In each iteration, the variable we have created for the loop will contain the value obtained on each index in the array we are working with.

Syntax: Declare for-each loop in Java

// for-each loop in java
for (data type variable_name : array) { 

      // for-each loop code block
}

Note that we use a colon, : , between the variable we create and the array we want to work with.

Syntax: For loop in Java to process an array

If we instead want to use the “standard” for loop to perform the same operation as with a for-each loop, we use the syntax

// for loop to go through an array
for (int i = 0; i < arrayName.length; i = i + 1) {

      // for loop code block
}

If we would break it down:

  • The initial value, int i = 0, is set to zero because the index in an array always starts at 0.
  • For the condition, we use the built-in function .length which gives us the length of an array, which we use to set up the condition that as long as the variable i is less than the length of our array arrayName, the loop shall be executed.
  • Finally, we increase the initial value by one, i = i + 1, for each step to process all the elements in our array.

Examples: For-each loop in Java

Let’s look at a few examples that demonstrate how we can use a for-each loop to process an array. We will also look at examples where we perform the same task using a for-each loop and the “standard” for-loop, so you get to see the differences between them.

Example 1: For-each loop to show the values in an array

Let’s start with a simple example where we loop through an Array containing five names.

public class Example{
   public static void main(String[] args) {
      String[] names = {"Jonas", "Lisa", "Ahmed", "Elin", "Lars"};           
   }
}

So we have an array called names containing elements of data type String (texts).

For-each loop Array Java programming

Figure 1: Example of an array in Java

We can easily loop through all the elements in the array by using:

public class Example{
   public static void main(String[] args) {
      String[] names = {"Jonas", "Lisa", "Ahmed", "Elin", "Lars"};     
      
      // for-each loop
      for (String val : names) { 
         System.out.println("Hi " + val); 
      }   
   }
}

That in this case results in:

Hi Jonas
Hi Lisa
Hi Ahmed
Hi Elin
Hi Lars

The variable Var changes with each iteration in the same order as they are placed in the array. If you want to try the example in an online compiler, use the button below

Example 2: Summarise all the elements in an array

In this example, we will try to sum all integers in an array. First, we create a variable that we name total and an array with name numbers containing four integers

public class Example{
   public static void main(String[] args) {

      int total = 0; 
      int [] numbers = {20, 33, 40, 55, 8, 99, 120};
   }
}

To calculate the sum of all numbers in the array, we can loop through all numbers with a for-each loop and save the sum in the variable total.

public class Example{
   public static void main(String[] args) {

      int total = 0; 
      int [] numbers = {20, 33, 40, 55, 8, 99, 120};

      for (int element : numbers){ 
         total = total + element; 
      }
   }
}

However, if we instead want to use the standard for loop, we use:

public class Example{
   public static void main(String[] args) {

      int total = 0; 
      int [] numbers = {20, 33, 40, 55, 8, 99, 120};

      for (int i = 0; i < numbers.length; i++){ 
         total = total + numbers[i];
      }
   }
}

Pay attention to that we use the built-in function length that gives us the size of an array, which we use to set the condition that; as long as i is smaller than the length of our array numbers, the loop shall be executed.

To conclude, in this case, both loops work just as well and provide the same answer.

375

Example 3: Print odd numbers in an array

Let’s take a third and final example. We again have an array called numbers that contains several different numbers. What we want to do is print all the odd numbers that are in the array numbers. Additionally, we also want to keep track of how many there are. Therefore, we create the variable count, which we use to keep track of how many odd numbers there are.

public class Example{
   public static void main(String[] args) {

      int count = 0; 
      int [] numbers = {1, 8, 7, 6, 4, 2, 12, 13, 5, 4, 2, 10, 22};
   }
}

Furthermore, we then create our for-each loop that goes loops through the array numbers. The variable we work with we named, as in example 2, elements. We use an if statement to check if the value of elements is evenly divided by 2. To do this, we use a modulus.

public class Example{
   public static void main(String[] args) {

      int count = 0; 
      int [] numbers = {1, 8, 7, 6, 4, 2, 12, 13, 5, 4, 2, 10, 22};

      for (int element : numbers) {

      if (element % 2 != 0){
         count++;
         System.out.println("Value: " + element + " in order: " + count);
      }
      
      System.out.println("\nTotal: " + count + " odd numbers");
      }
   }
}

To conclude, the result we get if we run the program in the example will be:

Value: 1 in order: 1
Value: 7 in order: 2
Value: 5 in order: 3
Value: 1 in order: 4
Value: 9 in order: 5
Value: 3 in order: 6

Total: 6 odd numbers

Differences between for-each loop and for loop in Java

There are a couple of differences between the for-each loop and the one we describe as the “standard” for-loop in Java.

  • A for-each loop is executed consecutively; in other words, there is no counter as there is in the standard for-loop. In the standard for-loop, you can change the steps to count, for example, i = i + 2, in other words, looping every other element in an array. This is not possible with an enhanced for loop
  • The for-each loop can only iterate (go through) the array in incremental order. So we can’t configure it to, for example, go through the array backwards. In the standard for-loop we can configure the counter backwards using, i- -, but a for-each loop always goes through the array in the order in which the elements are located
  • The for-each loop does not have access to the array index, which means that you cannot replace the element with the index. The standard for-loop, on the other hand, has access to the index, which then allows you to replace any element in the array

That was a few differences that are good to know. To summarize, if you need more control, select the standard for-loop. However, if you do not need that level of control, choose the more convenient option, the for-each loop.

Exercises: For-each loop in Java

Let’s look at a short quiz to make sure you understand how to declare and use the for-each loop in Java.

Code exercise 1: For-each loop

int num = 0;
int [] arr = {10, 24, 23, 69, 33, 18};

for (int element : arr){
    if (element > num){
        num = element;
        }
    }

System.out.println(num);

Answer exercise 1

Answer

Code exercise 2: For-each loop

int smallest = 0;
int [] arr = {10, 24, 23, 69, 33, 18};

for (int element : arr){
    if (smallest > element[arr]){
        smallest = elemen[arr];
        }
    }

System.out.println(smallest);

Answer exercise 2

Answer

Summary: For-each loop in Java

For-each loop, also known as enhanced for loop, is a way to efficiently and swiftly process all elements of an array. The difference between the for-each loop and the for loop is that a for-each loop operates on each element, instead of a specific number of times. Moreover, the for-each loop can only iterate the array in incremental order and is executed consecutively; in other words, you cannot take every other element in an array with the for-each loop, as you can with the “standard” for loop.

Syntax: for-each loop in Java

// for-each loop in java
for (data type variable_name : array) { 

      // for-each loop code block
}

Note that we use a colon,:, between the variable we create and the array we want to work with.

FAQ: For-each loop in Java

Do I have to use the for-each loop? Can’t I just use the regular for-loop all the time?

No, you don’t have to use the for-each loop. However, it can be useful to learn how a for-each loop works, for example, if you are working on a project with other developers and someone there who prefers a for-each loop

Is the for-each loop faster than a “standard” for loop?

Some suggest that the for-each loop may be faster than a “standard” for-loop in some cases. However, in many cases, it is almost the same. For the programs we develop, the speed between the loops should have an extremely marginal impact. If you want to read more about the discussion regarding speed between the for-each loop and the “standard” for loop, you can do so at this link

Does the for-each loop work in the same way as the “standard” for loop?

Both yes and no. The for-each loop can do the same thing as the regular for-loop but has a couple of limitations. First, an enhanced for-loop is executed in sequence; in other words, there is no counter like there is in the regular for-loop. Furthermore, enhanced for-loop can only iterate (pass-through) the array in incremental order; that is, it increases incrementally. So we can not configure it to, for example, go backwards through an array. Finally, an enhanced for-loop does not have access to the array index.