What is foreach Java loop?

What is foreach Java loop?

for loop is used to iterate any data in Java as in most of the languages. To make the iteration of elements easier, the general for loop can be replaced with a new loop known as foreach Java loop in JDK 1.5. But this new foreach Java loop should be used only in arrays and collections classes only.
The foreach Java loop with arrays is shown in Arrays Enhanced for loop and foreach with collections classes is shown in the following example with ArrayList.

foreach Java

Let us see how the new foreach loop works.

for(String str : al)
System.out.print(str + “, “);

In the new loop, the initialization, test condition and incrementing is done implicitly. In the first iteration, the first element of ArrayList al is copied into string str. Now str is printed. In the next iteration, the second element is copied and is printed and like this goes for all the elements.

Leave a Reply

Your email address will not be published. Required fields are marked *