Monday, September 13, 2021

Difference between for loop and Enhanced for loop in Java? Example Tutorial

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 easier 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 the looping process. All the differences, you will learn in this article, stems from the very fact that traditional for loop gives more control than 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 enhanced for loop as shown here.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.


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 a 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, whereas 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 the array should be displayed sequence in the forward direction and we also don't want to change the real value in the array accidentally 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 the 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 a loop and an 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 the iteration process then use traditional for loop.

With the introduction of the 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 the given array? (solution)
  • 10 Examples of forEach() in Java 8? (examples)
  • Top 22 Array concept Interview Questions (answer)
  • How do find the top two numbers from an integer array? (solution)

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

3 comments :

Unknown said...

Please clarify 2nd point .... I am not able to understand 2nd point

javin paul said...

Hello Himanshu, an object which holds other objects is commonly known as container. For example, Collection interface in Java or List, Set they hold other objects they are called container or collection class. In order for them to be used inside enhanced for loop, they must implement Iterable interface. This means if you write your own container, very low chance you can implement Iterable interface in order to make it usable with enhanced for loop.

Unknown said...

The "enhanced for loop" is not less powerful by any means. It only seems so because you are restricting yourself to iterating through an array. But the "enhanced for loop" allows you to iterate through any collection. Would you like to iterate through for loop through a binary tree? An n-ary tree? A cyclic graph? A set?

for (item i : myCollection) {
/* whatever you want */
}

Post a Comment