How to use for-each loops in Java
With the for-each Java loop you can traverse arrays and collections more quickly and safely, avoid errors and improve code readability. In this tutorial, we explain the structure and benefits of the for-each method in more detail and show you how to use the loop in your code.
What is the for-each Java loop used for?
The for-each loop is used in many scenarios where Java developers need to work with arrays. For example, a common use is to output or search for specific elements of an array. The for-each loop can likewise be used to iterate through elements in a list implemented as an ArrayList. In each iteration, you can perform automatic manipulations with common Java operators without having to write a separate statement for each element.
In contrast to the for loop in Java, when you use the for-each Java loop, you don’t need to consider the index or size of the array. Not having to consider these aspects means you avoid the risk of an index being outside of the valid range. The for-each loop internally uses an iterator to call up each element of the array or list one by one. The iterator automatically counts through the array or list and terminates the loop when all elements have been traversed.
If you, however, need to access the index to edit the next or previous element, it may make more sense to use the for loop or the while loop.
What is the syntax of the for-each Java loop?
The basic syntax of a for-each loop in Java looks like this:
for (type item : array | collection) {
// code block
}
Java-
array/collection
: Name of the array or collection -
item
: Each element of the array or collection is assigned to this variable -
type
: Data type of the array or collection
Inside the loop, the code block is executed for each iteration.
Examples of how to use the for-each Java loop
Below we’ll demonstrate how to use the for-each method using screen output and arithmetic operations.
Outputting elements to the console
Using the for-each loop, you can display each element of an array or collection on the screen.
class Main {
public static void main(String[] args) {
// array
String[] names = {"Sophie", "Alayna", "Miles", "Elliott", "Melissa"};
// for each loop
for (String name: names) {
System.out.println(name);
}
}
}
In the console, we get the output:
```Java
Sophie
Alayna
Miles
Elliott
Melissa
JavaIt is also possible to output the elements of a list analogically. The source code for the loop remains unchanged.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// list
ArrayList<String> names = new ArrayList<String>();
names.add( "Sophie" );
names.add( "Alayna" );
names.add( "Miles" );
names.add( "Elliott" );
names.add( "Melissa" );
// for each loop
for(String name: names){
System.out.println(name);
}
}
}
JavaA string is generated for each name from the list:
Sophie
Alayna
Miles
Elliott
Melissa
JavaCalculating the sum of elements in an array or collection
The for-each Java method makes it easy to carry out arithmetic operations such as adding the elements in an array or list. Operators are linked to the variable that serves as a placeholder for each element within the code block of the loop.
class Main {
public static void main(String[] args) {
// array
int[] numbers = {10, 34, 7, 19, -28};
int sum = 0;
// addition
for (int number: numbers) {
sum += number;
}
System.out.println("Result = " + sum);
}
}
JavaThe numbers of the array are added in sequence to the variable sum
, which was previously declared outside the loop. The output is:
Result = 42
Java