For-each in Java loop is another way for array traversing techniques like the  for loop,  while loop,  do-while loop introduced in Java 5. It starts with a keyword for like a normal for-loop. Instead of declaring and initializing the loop counter variable, you can declare the variable that is the same type as a base type of the array, followed by the colon, which is then followed by an array name.

In the loop body, you can use a loop variable you created rather than using an indexed array item. It’s commonly used to iterate over the  array or a  Collections class (e.g.,  ArrayList).

For-each Loop In Java

The Java for-each loop traverses the array or collection until the last element. For each item, it stores the element in the variable and executes the body of the for-each loop.

See the following syntax.

for (type item : collection) 
{ 
    statements using var;
}

In the above syntax,

  1. A collection is a collection or array variable that you have to loop through.
  2. An item is a single item from the collection.

#java #for-each loop

For-each Loop In Java Example | Java Foreach Tutorial
2.55 GEEK