Enhanced for Loop for Arrays

Learn about 'for each' loop and how it works in Java.

Java provides a special kind of for loop that can be used with arrays. This loop is much easier to write because it doesn’t involve an index variable or the use of []. Let’s get started.

The for each loop

Introduction

To set up a for each loop, look at the snippet below:

for (datatype variable: arrayname)

The datatype specifies the type of values in the array called arrayname. The variable refers to the enhanced for loop variable. It reads: for each variable value in arrayname.

Example

Let’s look at an example.

Press + to interact
class EnhancedLoop
{
public static void main(String args[])
{
int[] num = {1, 2, 3};
for (int n: num) // for each n in num
{
System.out.println(n); // Print n
}
}
}

Initially, we create an int type array. Look at line 7. We add the header for the for each loop (enhanced for loop), which reads: for each n in num. This means that the ...