The for-each loop is a simplified version of the for loop that is specifically designed to iterate over elements in an array or any other collection of data.
Syntax
for (type variableName : arrayName) { // code block to be executed }
Example
The following example demonstrates how to print all elements in a cars
array using a for-each loop:
String[] vehicles = {"Honda", "Toyota", "Chevrolet", "Mazda"}; for (String car : vehicles) { System.out.println(car); }
In this example, the for-each
loop iterates through each element in the vehicles
array and prints it.
Key Points
- The for-each loop is ideal for looping through arrays and collections as it simplifies code and reduces the chance of errors.
- It is particularly useful when you don’t need to access the index of the elements, but just need to process each element directly.