Java - Arrays and Enhanced for Loop

Introduction

The enhanced for loop has the following syntax:

for(DataType e : array) {
   // e contains one element of the array at a time
}

The following code uses a for-each loop to print all elements of an int array:

int[] numList = {1, 2, 3};
for(int num : numList) {
        System.out.println(num);
}

You can accomplish the same thing using the basic for loop, as follows:

int[] numList = {1, 2, 3};
for(int i = 0; i < numList.length; i++) {
    int num = numList[i];
    System.out.println(num);
}

You cannot access the index of the array element in Enhanced for Loop.

You cannot modify the value of the element inside the loop in Enhanced for Loop.

Demo

public class Main {
  public static void main(String[] args) {
    int[] numList = {1, 2, 3};
    for(int num : numList) {
            System.out.println(num);
    }/*from   w w w.  j ava 2  s  . c om*/

  }
}

Result