Keywords: for-each loop, enhanced for loop, array, for loop
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.
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.
To create a for-each loop, we use a similar syntax as we use with the for loop.
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.
// 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.
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:
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.
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).
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
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
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
There are a couple of differences between the for-each loop and the one we describe as the “standard” for-loop in Java.
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.
Let’s look at a short quiz to make sure you understand how to declare and use the for-each loop in Java.
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
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
Please leave feedback and help us continue to make our site better.
How useful was this article?
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?
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.
// 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.
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
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
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.