Difference Between for loop and Enhanced for loop in Java - GeeksforGeeks

10 Feb, 2022
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 classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass 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 compile–time 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 classesimport java.io.*;import java.util.*; // Classclass 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);        }    }}
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. 
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...)
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);
}
}
 
saurabh1990aror
surinderdawra388
sagar0719kumar
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples