Java for-each Loop

In this tutorial, we will learn to use for-each loop to iterate(loop) through the element in an array.

Syntax

for (data_type variable_name : array) {
  // block of code to be executed.	
}

Here,

  • data_type is the type of the array
  • variable_name is name of the variable to which each item will be assigned.
  • array - This is the array which contains collection of values of similar data type.

Example

class Main {
  public static void main(String[] args) {
      
    // create an array with initial values.
    int[] numbers = {1,3,4,5,7,8};
    
    // for-each loop to print each numbers.
    for (int number: numbers) {
      System.out.println(number);
    }
  }
}

Output

1
3
4
5
7
8

In the above program, we initialize an integer array numbers with set of initial values.

Next, using the for-each loop, we loop through the numbers array.

For each iteration(loop) the value is assigned to the number variable which is then printed to the console.

Note: Since the numbers array is of type integer the variable that get the values of this array should be also of type integer. If we assign to different datatype it will throw an error.


Most Read