The for-each loop was introduced in Java 5. Actually, the loop is a
for loop with a
: placed between a variable and a data structure such as an array. Each item of the data structure is stored in the variable per loop iteration. The loop terminates when the final item has been processed. To understand how to write for-each loops in Java, follow these four steps.
- Open your text editor and type in the following Java statements:
The program creates and initializes an array of names. Next, the program uses a for-each loop to display each array element. Notice that the for-each loop stores each item of the
namesarray in the
namevariable for each iteration of the loop.
- Save your file as WriteForEachLoops.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Now test your program. Type in the command to run the Java runtime launcher and then hit Enter. Notice the output of the program verifies that each array has been successfully processed by the for-each loop.