Usage of Java foreach statement

Usage of Java foreach statement

foreach loop statement is one of the new features of Java 1.5. foreach provides great convenience for developers in traversing arrays and collections. foreach loop statement is a special simplified version of for statement, which is mainly used to execute the loop of traversal function.

The syntax format of foreach loop statement is as follows:

for(Type variable name:aggregate) {
    Statement block;

Among them, "type" is the type of collection elements, "variable name" represents each element in the collection, and "collection" is the collection object or array to be traversed. Each time the loop statement is executed, the loop variable reads an element in the set, and its execution process is shown in Figure 1.

Figure 1 execution flow chart of foreach loop statement

Example 1
Suppose there is an array. The way to traverse the array with the for statement is as follows:

// Declare and initialize arrays
int[] numbers = { 43, 32, 53, 54, 75, 7, 10 };
// for statement
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Count is:" + numbers[i]);

The statement in line 2 above declares and initializes seven element array sets. At present, you only need to know that when initializing the array, you should put the elements of the same type into {...} and separate them with commas (,).

The array collection will be introduced in detail later in the tutorial. Here we only need to know about it. numbers.length is to obtain the length of the array, length is the attribute of the array, and numbers[i] is to access the array elements through the array subscript.

Then, use the for each loop statement to traverse the array as follows:

// Declare and initialize int array
int[] numbers = { 43, 32, 53, 54, 75, 7, 10 };
System.out.println("----for each----");
// For each statement
for (int item : numbers) {
    System.out.println("Count is:" + item);

It can be found from the example that item is not a circular variable. It saves the elements in the set. The for each statement takes out the elements in the set one by one and saves them to item. In this process, there is no need to use circular variables to access the elements in the array through the array subscript. It can be seen that the for each statement is much simpler and more convenient when traversing the collection.

Example 2

String[] urls = { "", "", "" };
// Iterate through array elements using foreach
// book will automatically iterate over each array element
for (String url : urls) {

As can be seen from the above program, there is no need to obtain the array length or access the array elements according to the index when using the foreach loop to traverse the array elements.

The difference between foreach loop and ordinary loop is that it does not need loop conditions and loop iteration statements. These parts are completed by the system. Foreach loop automatically iterates each element of the array. When each element is iterated once, the foreach loop automatically ends.

When using foreach loop to iterate the output array elements or set elements, it is usually not necessary to assign a value to the loop variable. Although this assignment is allowed in syntax, it has little practical significance and is very easy to cause errors. For example, the following procedure.

String[] urls = { "", "", "" };
// Use the foreach loop to iterate through the array elements, where book will automatically iterate over each array element
for (String url : urls) {
    url = "";

Run the above program and you will see the following results:

From the above running results, due to the assignment of array elements in the foreach loop, the array elements cannot be traversed correctly and the value of each array element cannot be extracted correctly. Moreover, when the first array element is accessed again, it is found that the value of the array element remains unchanged.

It is not difficult to see that when using foreach to access array elements iteratively, the circular variable in foreach is equivalent to a temporary variable, and the system will assign the array elements to this temporary variable in turn. This temporary variable is not an array element, but only saves the value of the array element. Therefore, you cannot use this foreach loop if you want to change the value of an array element.

When using foreach loop to iterate over array elements, the value of array elements cannot be changed, so do not assign a value to the loop variable of foreach.

Example 3
Several programming languages are stored in a string array. Now traverse the output of these programming languages.

The implementation code of foreach statement is as follows:

public static void main(String[] args) {
    String[] languages={"Java","ASP.NET","Python","C#","PHP"};
    System.out.println("The popular programming languages are:");
    // Use the foreach loop statement to traverse the array
    for(String lang:languages) {

During the execution of the loop body, each time the loop is executed, an element in the languages array will be assigned to the lang variable until all elements in the languages array are traversed and the loop ends.

The results after running the program are as follows.

The popular programming languages are:

Keywords: Java Back-end

Added by Spud_Nic on Tue, 15 Feb 2022 03:51:44 +0200