Java Foreach Loop Guide

In Java, the forEach statement is a convenient method for iterating through arrays or collections. Its syntax is:

for (元素类型 元素变量 : 数组或集合) {
    // 执行代码
}

The element type is the data type of the elements in the array or collection, the element variable is the variable name used to store each element, and the array or collection is the data structure to be traversed.

Here is an example demonstrating how to use a foreach statement to iterate through an array.

int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
    System.out.println(number);
}

In this example, we have defined an array called numbers containing integers and are using a foreach statement to iterate through each element in the array and print it out. The output result is:

1
2
3
4
5

Similarly, we can use a foreach statement to iterate through a collection, such as ArrayList.

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

for (String name : names) {
    System.out.println(name);
}

In this example, we have defined an ArrayList called names containing strings, and we are using a foreach statement to iterate through each element in the collection and print them out. The output result is:

Alice
Bob
Charlie

By using the foreach statement, we can efficiently iterate over arrays or collections and perform operations on their elements.

bannerAds