Java - for-each Statement

What is for-each Statement"

for-each loop iterates over elements of arrays and collections.

Syntax

The general syntax for a for-each loop is as follows:

for(Type element : a_collection_or_an_array) {
   // executed once for each element in the collection/array.
}

Example

The following snippet of code prints all elements of an int array numList:

Demo

public class Main {
  public static void main(String[] args) {
    int[] numList = { 10, 20, 30, 40 };
    for (int num : numList) {
      System.out.println(num);//w w w. ja v a  2  s .c om
    }

  }
}

Result

Related Topics

Exercise