What is the usage of the foreach loop in Java?
In Java, the foreach loop (also known as the enhanced for loop) is used to iterate through elements in an array or collection, providing a simple and convenient way to access elements during iteration.
The syntax format of a foreach loop is as follows:
for (元素类型 元素变量 : 数组或集合) {
// 执行语句
}
In this case, the element type refers to the data type of the elements in an array or collection, and the element variable is a temporary variable used to store the value of each element.
During each iteration of the loop, the element variable is automatically assigned the current element in the array or collection, and the statements in the loop body are then executed. The loop will sequentially iterate through each element in the array or collection until all elements have been traversed.
Below are some common ways to use a foreach loop:
- Iterate through the elements of an array.
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
System.out.println(num);
}
- Iterate through the elements in a collection.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name);
}
- Calculate the sum of elements in an array or set.
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : nums) {
sum += num;
}
System.out.println("Sum: " + sum);
Please note that the foreach loop is read-only, meaning you cannot modify the elements in an array or collection within the loop. If you need to modify the elements, you can use a traditional for loop instead.