How does the Java 'for each' loop work?
The Java for-each
loop, also known as the enhanced for
loop, is a convenient way to iterate over the elements of an array or a collection. It eliminates the need to use an index variable to access the elements of the collection.
Here is the syntax for a for-each
loop:
for (type variable : array or collection) {
// statements using variable
}
The type
specifies the type of the elements in the array or collection, and variable
is a new variable that will be created for each iteration of the loop. The array or collection
is the array or collection that you want to iterate over.
Here is an example that shows how to use a for-each
loop to iterate over the elements of an array of integers:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
This will print the numbers 1, 2, 3, 4, and 5, each on a separate line.
In the for-each
loop, the variable number
is assigned the value of each element in the numbers
array in turn, starting with the first element and ending with the last. The loop continues until all elements have been processed.
You can also use a for-each
loop to iterate over the elements of a collection, such as a list or a set. For example:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
This will print the names "Alice", "Bob", and "Charlie", each on a separate line.