English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Java Exception Handling

Java 列表(List)

Java 队列(Queue)

Java 映射集合

Java 集合

Java 输入输出(I/O)/O)

Java 读取器/作家

Other Java topics

Java for-each loop (traversal loop)

In this tutorial, we will learn about another form of for loop in Java, that is, the enhanced for loop or for-each loop.

In Java, when dealing with arrays and collections, we can use the enhanced form of the for loop. Also known as for-Each loop. This is because the loop will traverse each element of the array or collection.

To understand the for-Before using the each loop, make sure you understand:

for loop and for-Differences between each loops

Why prefer for-Instead of the for loop, let's look at the following example using the each loop.

In this example, it shows how to use the standard for loop to traverse the elements of an array.

class ForLoop {
    public static void main(String[] args) {
      
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (int i = 0; i < vowels.length; ++ i) {
            System.out.println(vowels[i]);
        }
    }
}

Output:

a
e
i
o
u

Now, we will use for-The each loop performs the same task.

class AssignmentOperator {
   public static void main(String[] args) {
      
      char[] vowels = {'a', 'e', 'i', 'o', 'u'};
      // foreach loop
      for (char item: vowels) {
         System.out.println(item);
      }
   }
}

Output:

a
e
i
o
u

Here, we can see that the output of the two programs is the same.

When we analyze these two programs carefully, we can notice that the for-The each loop is easier to write and makes our code more readable. This is why it is called the enhanced for loop.

Therefore, it is recommended to use the enhanced for loop as much as possible in the standard for loop.

Java for-Each loop

Let us first look at the for-Syntax of the each loop:

for(data_type item : collections) {
    ...
}

Here,

  • collection -The collection or array you need to traverse.

  • item -A single item in the collection.

for-How does the each loop work?

Execute for each iteration-Each loop, which is for-How the each loop works in Java.

  • Iteration - Traverses each item in the given collection or array (collections)

  • Stores - Each item in the variable (item)

  • AndExecutes repeatedlyThe main statement inside the loop.

Let us illustrate this clearly with an example.

Example: for-Each loop

This program calculates the sum of all elements in an integer array.

class EnhancedForLoop {}}
    public static void main(String[] args) {
      
        int[] numbers = {3, 4, 5, -5, 0, 12};
        int sum = 0;
      
        for (int number: numbers) {
            sum += number;
        }
      
        System.out.println("Sum = ", + sum);
    }
}

Output:

Sum = 19

In the above program, for-The execution of the each loop is as follows:

IterationValue
1number = 3 When, sum = 0 + 3 = 3
2number = 4 When, sum = 3 + 4 = 7
3number = 5 When, sum = 7 + 5 = 12
4number = -5 When, sum = 12 + (-5) = 7
5When number = 0, sum = 7 + 0 = 7
6number = 12 When, sum = 7 + 12 = 19

You can see the for in each iteration.-Each loop

  • Traverse each element in the numbers array.

  • Store it in the number variable.

  • And execute the main body, and add the number to the variable sum, and finally get the total number (sum).