Difference between for loop and Enhanced for loop in Java

Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list, set, or map. There are some key differences between them. In general, enhanced for loop is much more easy to use and less error prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control over looping process. All the difference, you will learn in this article, stems from this very fact that traditional for loop gives more control that enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience.

So, the choice is up to you, if you need more control then traditional for loop is ideal and if you don't need that level of control, just opt for convenience by using enhance for loop as shown here.


Difference between for loop and advanced for loop in Java

Let's see some key differences between traditional for loop and enhanced for loop of Java 5. This will help you to understand the concept better and take decision 

1) The for loop is present from the start i.e. JDK 1, but enhanced for loop was added on Java 5, hence it's only available from JDK 5 onward.


2) 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.

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+2; to loop every second element in an array or collection.

3) The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrement. i.e in for loop we can write i-- in step counter to go backward.

4) 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 any element in the array.

5) If we have a requirement that array should be displayed sequence in the forward direction and we also don't want to change the real value in the array accidently or intentionally by any user etc then we should use the enhanced for loop.

6) Since Java 8, you can also use the forEach() method to iterate over a collection in Java. This method is added in both Iterable and Stream interface to allow seamless iteration using functional programming idiom.



Here is the sample program to demonstrate how you can use both for loop and enhanced for loop to iterate over an array and a list in Java.


Iterating over a list in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class App {

  public static void main(String args[]) {

    List<String> gadgets = new ArrayList<>(
        Arrays.asList("Apple watch", "Samsung Gear 3", "iPhone 7+"));

    // iterating over List using for loop
    System.out.println("iterating over a List using for loop in Java:");
    for (int i = 0; i < gadgets.size(); i++) {
      System.out.println(gadgets.get(i));
    }

    // iterating over List using enhanced for loop
    System.out.println("iterating over a List using enhanced for loop in Java:");
    for (String gadget : gadgets) {
      System.out.println(gadget);
    }
  }

}

Output
iterating over a List using for loop in Java:
Apple watch
Samsung Gear 3
iPhone 7+
iterating over a List using enhanced for loop in Java:
Apple watch
Samsung Gear 3
iPhone 7+

You can see that elements of a list are displayed in sequence using both traditional and enhanced for loop in Java. Now, let's see how to iterate over an array in Java using both kinds of loops in Java:

Difference between for loop and Enhanced for loop in Java


Iterating over an array in Java

/**
 * Java Program to iterate over an array
 * using for loop and enhanced for loop in Java
 * @author WINDOWS 8
 *
 */
public class App {

  public static void main(String args[]) {

    int[] cubes = {1, 4, 9, 16, 25, 36};

    // iterating over an array using for loop
    System.out.println("iterating over an array using for loop in Java:");
    for (int i = 0; i < cubes.length; i++) {
      System.out.println(cubes[i]);
    }

    // iterating over an array using enhanced for loop
    System.out.println("iterating over an array using enhanced for loop in Java:");
    for (int cube : cubes) {
      System.out.println(cube);
    }
  }

}

Output
iterating over an array using for loop in Java:
1
4
9
16
25
36
iterating over an array using enhanced for loop in Java:
1
4
9
16
25
36


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. With the introduction of forEach() method in Java 8, you now have three for loop sort of construct to loop over an array or collection in Java. See this article to learn more about the journey of the for loop in Java i.e. from for(; index; ) to enhanced for loop to forEach().


Other Java array tutorials you may like
  • Top 30 Array-based Coding Questions from Interviews (list)
  • What Every Java Programmer should know about the array? (article)
  • The difference between an array vs ArrayList in Java? (answer)
  • 2 ways to find duplicate elements in given array? (solution)
  • 10 Examples of forEach() in Java 8? (examples)
  • Top 22 Array concept Interview Questions (answer)
  • How to find top two numbers from integer array? (solution)

Further Reading
Java SE 8 for Really Impatient by Cay S. Horstmann
Java: A Beginner's Guide by Herbert Schildt


Thanks for reading this tutorial, if you like this tutorial then please share with your friends and colleagues. If you have any suggestion or feedback then please drop a comment. 


No comments :

Post a Comment