In this article, we’ll go through what for each loop in Java is, and how you can use it.
1. What is a For Each Loop
For Each Loop is like the classic for loop, but with a much simpler syntax than the classic for a loop as you only need to know the name and the type of the collection that you need to loop through. Furthermore, for-each
loop can be used to iterate through an array or any collection.
Finally, as with for loops, you can use the break
or continue
keyword, to exit or skip the current iteration. Note that you can also return a value back to the method caller inside a for each loop (and interrupt the loop), by using the return
keyword.
2. Java For Each Loop Syntax
For-each loop syntax is pretty simple:
It consists of the for
keyword, and 2 parentheses. Then, inside the parenthesis, you need to declare the type of items the collection or the array you need to loop through has and a name for the variable that you can use inside this loop. Lastly, you need to specify the name of the collection or array that you will loop through.
for (Object_type_or_primitive local_var_name : a_collection_or_array_name) { //code }
As you can observe from the syntax above, we do not have any index as we have in for loops. Consequently, this makes for-each loop read-only as you cannot change the value of any collection or an array through its index.
3. How to Write a For Each Loop in Java
Now that we know the syntax of for each loop
, we can go through how you can use it with collections or an array.
3.1 Using For Each Loop With an Array
First of all, if you don’t know much about arrays, you can check this article.
Now let’s jump to an example:
int[] numbers = new int[]{1, 2, 3, 4, 5}; for (int i : numbers) { System.out.println(i); } String[] clh = new String[]{"Code", "Learn", "Hub"}; for (String s : clh) { s = s.toUpperCase(); } for (String s : clh) { System.out.println(s); }
The output will be:
1 2 3 4 5 Code Learn Hub
As you can see, even though we changed the value of s in the second loop to be uppercase, this change did not affect the values inside the array, confirming the fact that indeed for-each loops are read-only.
2.2 Using For Each Loop With Collections
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); for (Integer number : numbers) { System.out.println(number); } Set<String> clh = Set.of("C", "L", "H"); for (String s : clh) { System.out.println(s); }
2.3 Using For Each Loop With a Map
When it comes to maps, we should choose if we want to loop through the keys or the values, as for each loop supports only one variable at a time. Below you can find an example:
Map<Integer, String> map = Map.of(1, "C", 2, "L", 3, "H"); System.out.println("Printing keys:"); for (Integer key : map.keySet()) { System.out.println(key); } System.out.println("Printing values:"); for (String s : map.values()) { System.out.println(s); }
The output will be the following:
Printing keys: 1 2 3 Printing values: C L H
4. ConcurrentModificationException in Java For Each Loop
You need to be careful when using the for-each loop and not modify the collection by adding or removing elements while you are inside the for-each loop. Consider the example below, where we want to remove every element inside a for-each loop:
List<String> s = new ArrayList<>(); s.add("1"); s.add("2"); s.add("3"); s.add("4"); for (String s1 : s) { s.remove(s1); }
If you do try to run this, you will get Exception in thread "main" java.util.ConcurrentModificationException
. ConcurrentModificationException
is an exception that is thrown because you tried to modify the list while you were performing another task to it – traversal via for each loop.
5. Conclusion
By now, you should be able to use a for-each loop when it is needed. You can find the source code on our Github page.