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:
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.