For Each Loops (Iteration)
Welcome, this page will teach you how to create a For Each Loop in Java.
What is a For Each Loop?
A For Loop is very similar to a For Loop within Java except it only requires two arguments and instead of referring to the current value of the loop through the index, we have an actual item.
When are For Each Loops used?
For Each Loops are used for iterating through a list of values or items and performing an action on each of them individually. For example; if you wanted to change the boolean "active" of each item to true.
Why not just use a For Loop?
For Each Loops make it slightly easier to iterate through a list of values or items as it gives us an actual item to use as a reference, instead of just an index id or integer to be used. For Each Loops tend to be used for iterating through actual lists or arrays in Java, whereas For Loops tend to just be used for performing actions with a row of different integers.
Here is an example of an Array of String items which is looped through using a For Each Loop to output each String to the console...
Which gives the output:
Hello Hey Hi
You are able to also use a version of indexing while using it as a For Each Loop. This only works for ArrayLists (as opposed to arrays) and can be achieved through: