For-Each Loops
For-Each loops are different from the other loops mentioned in Loops, as they are specifically designed for traversing an array (accessing every element).
Let's say this was an array that you wanted to traverse through.
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};If you wanted to add one to each value, for instance, your code needs to know several properties of the array. If you wanted to execute this with a for-loop, you'd need to know the start and length, just to name a few.
This will become very bothersome. To tackle this problem, the creators of Java implemented a simple solution for you.
for (int num : arr) {
System.out.println(num + ", "); /* output: 1, 2, 3, 4, 5, 6, 7, 8, */
}Here's the syntax:
for (Object item : Object[] collection) {
[code]
}You might be wondering why I'm putting "Object" here as the type. This is because as long as the collection stores two items in an array of some sort, this loop can work on it.
Item
This is the current item that the for-each loop is on. However, you can only access its value— you can't change it or anything.
Collection
This is just the collection that the for-each loop is traversing through. The collection can be basically anything that can hold more than one value.
Last updated