Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaDifference Between for loop and Enhanced for loop in Java

Difference Between for loop and Enhanced for loop in Java

Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice.

Syntax:

for( initializationsection ; conditional check ;  increment/decrement section)
   {
    // Code to be executed
   }

Curly braces in for loop is optional without curly braces in for-loop we can take only one statement under for-loop which should not be a declarative statement and if we write declarative statement there then we will get compile-time error.

Example

Java




// Java Program to illustrate the use of
// for loop
 
// Importing all input output classes
import java.io.*;
// Importing all classes from
// java.util package
import java.util.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // 1st for-loop
        // Iteration ocer 5 elements using for loop
        for (int i = 1; i <= 5; i++) {
 
            // Print statement
            System.out.println("GFG!");
        }
 
        // 2nd for-loop
        // Declaring and initialization a variable
        // so we will get compile time error
        for (int i = 1; i <= 1; i++)
            int x = 0;
    }
}


 
 Output: 

Case 1: Absence of second for-loop 

GFG
GFG
GFG
GFG
GFG 

Case 2: Presence of second for-loop 

prog.java:28: error: variable declaration not allowed here
         int x=0;
             ^
1 error 

Output explanation:  

  • In the Initialization section, This part will be executed only once in the loop life cycle. Here we can declare and initialize a local variable for loop. Here we can declare any number of variables but should have the same type by mistake if we are trying to declare a different data type then we will get a compiletime error. In this section, we can take any valid java statement including ‘System.out.println()’.
  • During the condition check, we can take any valid java expression that should be of type boolean. This part is optional and if we are not taking anything then the compiler will always place a true value here.
  • In the Increment/Decrement section, we can either increment or decrement we can the initialized value. In this section we can take any valid java statement including ‘System.out.println()’ and this section is also optional.

Enhanced for loop(for-each loop)

This for-loop was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing array or collections. This loop also makes the code more readable and reduces the chance of bugs in the code.

Syntax:

for(data-type variable : array | collection)
  {
   // Code to be executed
  }  

Example: 

Java




// Java Program to show usage of for-each loop
 
// Importing all classes from
// java.util package
// Importing all input output classes
import java.io.*;
import java.util.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing the integer array
        // Custom integer entries in an array
        int[] array = { 1, 2, 3, 4, 5, 6 };
 
        // Accessing the element of array
        // using for-each loop
        for (int a : array) {
            // Print all elements of an array
            System.out.println(a);
        }
    }
}


Output

1
2
3
4
5
6

 After visualizing both the programs we landed upon some conclusive differences which are depicted in tabular format to get a clear understanding hand in hand. 

Normal for-loop Enhanced for-loop
This for-loop is present from JDK1 This for loop is present from JDK5

In a normal for-loop, we can increase the counter as per our wish by using

 i=i+x( where x is any constant x=1,2,3…)

But enhanced for loop will execute in a sequential manner i.e counter will always increase by one.
Using this for loop we can iterate on any container object. We can only iterate on that container by using this loop to implement the iterable interface.
In this for-loop, we can iterate in both decrement or increment order. But in this for-loop, we can iterate only in increment order.
In this for-loop, we can replace elements at any specific index. But in this for-loop, we don’t have access to the index, so we cannot replace elements at any specific index.
By using normal for-loop we can print array elements either in the original order or in reverse order. But in the for-each loop, we can print array element only in the original order, not in reverse order

Example: Printing element in a 1D array 

int[ ] x={1,2,3};

for(int i=0;i<x.length;i++)

{

   System.out.println(x[i]);

}

Example: Printing element in a 1D array using for-each loop 

int[ ] x={1,2,3};

for(int a :  x)

{

  System.out.println(a);

}

Example: Printing element in a 2D array using for loop

int[ ][ ] x={{1,2,3},{4,5,6}};

for(int i=0;i<x.length;i++) {

for(int j=0; j<x[i].length;j++) {

System.out.println(x[i][j]);

}

}

Example: Printing element in a 2D array using for-each loop

int[ ][ ] x={{1,2,3},{4,5,6}} ;

for(int[ ] x1 :x){

for(int x2 : x1) {

System.out.println(x2);

}

}

 

RELATED ARTICLES

Most Popular

Recent Comments