What is Difference between Loop and Enhanced Loop in Java

We have used both loop and enhanced loop to iterate over arrays and collections like a list, set, or map. There are many differences between them like- enhanced for loop is much more easy to use than for loop. In for loop you need to manage the steps manually. But at the same time, for loop is much more powerful because you get the opportunity to control over looping process.
In this tutorial, You will learn about the differences between both of the loops.

 

Difference between Loop and Enhanced Loop

Let’s see the differences between the Loop and Enhanced loop. It will help you to understand the concepts of Java :

  1. The for loop is present from the start i.e. JDK 1, but enhanced for loop was introduced with Collection Framework on Java 5, hence it’s only available from JDK 5 onward.
  2. The enhanced for loop executes in sequence. i.e  the counter is always increased by one, where as in for loop you can change the step as per your wish e.g doing something like i=i+3; to loop every third element in an array or collection. Basically, you can customize the execution order in for loop which is not possible with enhanced for loop.
  3. The enhanced for loop can only iterate in incremental order. We cannot configure it to go in decrement. But just opposite in for loop we can write i– in step counter to go backward.
  4. In order to loop over a container using enhanced for loop, your container must implement the Iterable interface, both array and collection implement this, but there is no such requirement for traditional for loop.
  5. You don’t have access to array index in enhanced for loop, which means you cannot replace the element at giving the index, but for loop provide access to the index, hence allows you to replace and modify any element in the array.

 

Let’s share an example to demonstrate how you can use for loop and enhanced for loop to iterate over an array and a list in Java.

Output :

 

You can see that elements of a list are displayed in sequence using both traditional and enhanced for loop in Java.

 

That’s all about the difference between for loop and enhanced for loop in Java. If you only want to iterate over elements from an array or a collection e.g. a list or a set then use enhanced for loop, it’s convenient and less error prone, but if you want more control over iteration process then use traditional for loop.

0 Comment

Leave a Reply