Java For-Each Loop

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.

Tutorials dojo strip



Syntax

JAVA




Example

The following example demonstrates how to print all elements in a cars array using a for-each loop:

JAVA

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.

Tutorials dojo strip