Java Array ForEach

Java For-each statement executes a block of statements for each element in a collection like array.

To iterate over a Java Array using forEach statement, use the following syntax.

</>
Copy
for( datatype element : arrayName) {
    statement(s)
}

datatype is the datatype of elements in array. You can access each element of array using the name element. Or you may give another name instead of element. You will understand the syntax when we go through examples.

In this tutorial, we will learn how to iterate over elements of array using foreach loop.

ForEach statement is also called enhanced for loop in Java.

The advantage of for-each statement is that there is no need to know the length of the loop nor use index to access element during each iteration.

Example 1 – Iterate over Java Array Elements using For-Each

In the following program, we initialize an array of integers, and traverse the elements using for-each loop.

Java Program

</>
Copy
public class ArrayExample {
	public static void main(String[] args) {
		int[] numbers = {2, 4, 6, 8, 10};
		for (int n: numbers) {
			System.out.println(n);
		}
	}
}

During each iteration of for loop, you can access this element using the variable name you provided in the definition of for-each statement. In the above program, we used the variable n, to store current element during this iteration.

Output

2
4
6
8
10

Example 2 – Iterate over Java String Array using For-Each

In the following program, we initialize an array of strings, and traverse the elements using for-each loop.

Java Program

</>
Copy
public class ArrayExample {
	public static void main(String[] args) {
		String names[] = {"apple", "banana", "cherry", "mango"};
		for(String name: names) {
			System.out.println("Hello " + name + "!");
		}
	}
}

During each iteration of for loop, you can access this element using the variable name you provided in the definition of for-each statement. In the above program, we used the variable n, to store current element during this iteration.

Output

Hello apple!
Hello banana!
Hello cherry!
Hello mango!

Conclusion

Concluding this Java Tutorial, we learned how to use Java for-each looping statement to execute block of statements for each element in given array.