Starting in the 2000’s when computers started to get faster, a lot of languages added a new type of loop, that is faster to write for the developer, but often a little slower to run. However, because of the new found computer speed, it wasn’t deemed to be a major issue.
That loop was called the for-each loop.
Basically it took the idea of the for loop, and said, “if we know these elements are in a row, why can’t we just iterate through them one at a time.” Once one language could do it, more and more started adding this feature.
You can think of it as “For each element in an array, do this set of instructions” and that is how it basically works.
General Example
Let’s take a look at how a general example might look:
int arr[] = {1,3,5,7,9,11,13,15,17,19};
for(int tmp: arr) {
// loop body
System.out.println(tmp);
}
Notice that it starts with for, just like a for loop, and has a loop body just like the for loop. The difference is within the parenthesis.
Here you have to define the temporary variable which will be holding the current element, as well as the array that is being passed in. Between these two items, you will notice a colon (:).
The above loop is functionally equivalent to the follow, standard style for loop.
int arr[] = {1,3,5,7,9,11,13,15,17,19};
for(int i =0; i< arr.length; i++) {
int tmp = arr[i]; // this is unnecessary normally, but need to make the two equivilent.
System.out.println(tmp);
}
Limitations with Java’s for-each Style Loop
You will need to have the current element stored in a variable. This is easy with how Java does the for each loop. However, it also creates some limitations.
First, this is a temporary duplicate, and changes to the variable will not be stored within the array.
Second, you have no way of knowing what element in the array you are working with. All you know for sure, is that you are in the array.
Third, as was mentioned above, you will have a performance hit when using this style loop.
With these limitations, you might wonder if it is right for you, and that just depends upon the needs of your application.
The For-Each Loop in Java was originally found on Access 2 Learn