Curriculum
In Java, the foreach loop is a control flow statement that allows you to iterate over the elements of an array, a collection, or any other type that implements the Iterable interface. The syntax of a foreach loop is as follows:
for (type variable : collection) {
// code to be executed for each element in the collection
}
The type is the data type of the elements in the collection, and the variable is a variable that represents each element in the collection during each iteration of the loop. The collection is the array, collection, or other type that implements the Iterable interface that is being iterated over.
Here’s an example of a simple foreach loop that iterates over an array:
int[] numbers = { 1, 2, 3, 4, 5 };
for (int number : numbers) {
System.out.println(number);
}
In this example, the foreach loop iterates over the elements of the numbers array. During each iteration, the current element is assigned to the loop variable number, and the value of number is printed to the console.
Here’s another example of a foreach loop that iterates over a collection:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
In this example, the foreach loop iterates over the elements of the names collection, which is a list of strings. During each iteration, the current element is assigned to the loop variable name, and the value of name is printed to the console.