Member-only story
Hi everyone, welcome back. In this tutorial, we will be going over the For-Each loop in Java. The for-each loop can be used to iterate through a collection of data such as an ArrayList. The for-each loop has similar capabilities to be for loop and while loop, but the for-each loop does not require a loop counter, making it a great choice when wanting to iterate through every element. With this introduction out of the way, let’s get into it.
For-Each Loop Example
We will start this by creating an array and then using the for-each loop to iterate through it to print each element individually. Let’s see how it’s done:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers){
System.out.println(num);
}Output:
1
2
3
4
5
As we can see in the example above, we have successfully managed to iterate through each individual element and print them. We can see that the syntax of the for-each loop still uses the ‘for’ keyword, however instead of creating a loop counter, we create a new variable of the same data type as our collection. Then we use a colon and use the variable name of our collection we wish to iterate through.
Conclusion
That is it for the for-each loop example. It’s fairly simple to use and it’s easier and faster to write compared to a standard for loop. I hope this helps. If there are any questions or comments, please let me know. Thanks for reading.