Enhanced for loop in Java

General format

for(datatype variable_name : array_name) {

//statements or code to be executed

}

This can be used to iterate or loop through arrays.

It is also called as for each loop since it iterates through each element of arrays.


Example

public class EnhancedForLoop {

public static void main(String args[]) {

int[] num={1,2,3,4,5};

for(int n: num) {

System.out.println(n);

}

}

}

Try In Editor

Output

1

2

3

4

5

In the above example variable n in for loop is initialized with every element of the array one by one till the size of the array.