Understanding the Java For Each Loop: Simplified Iteration for Arrays

Discover the simplicity of the for-each loop in Java, designed for effortless iteration through elements in arrays and collections. This powerful construct enhances code readability and reduces the likelihood of errors. Learn how to effectively implement the for-each loop in your Java programs with examples and best practices.



Java For Each Loop

A "for-each" loop is used to loop through elements in an array:

Syntax

for (type variableName : arrayName) {
// code block to be executed
}

The example below outputs all elements in the cars array:

Example

String[] cars = {"Tata", "Maruti", "Honda", "Hyundai"};
for (String i : cars) {
System.out.println(i);
}
Output

Tata
Maruti
Honda
Hyundai

Note: You will learn more about Arrays in the Java Arrays chapter.