Another type of for loop in Java is the enhanced for loop or for-each loop. This page is only a quick introduction since you will dive deeper into the subject after you've learned about Java Collections.
How Does the For-Each Loop Work?
The for-each loop is used to iterate over a collection of variables such as arrays. The form of the for-each loop is as follows.
for(type iteration-variable : collection){
// executable code
}
For-Each Loop Java Example
To iterate an array collection, the following loop would print out each variable inside of collection.
class Main {
public static void main(String[] args){
String[] collection = {"This", "is", "a", "collection"};
for(String item : collection){
System.out.println("The item is: " + item);
}
}
}
Now that you're aware of the existence of for-each loops, there are still several missing parts to your introduction to conditional flow control before you dive into collections.
Summary: Java For-Each Loop
The for-each loop in Java is similar to the for loop, except its syntax is specifically set to iterate over a collection.
Syntax
Here's the syntax for the for-each loop, where you can substitute the variables starting with your_ with your values.
for(your_variable_type your_item_name : your_collection){
// executable code
}