The Wayback Machine - https://web.archive.org/web/20240914130437/https://www.geeksforgeeks.org/difference-between-for-loop-and-enhanced-for-loop-in-java/
Open In App

Difference Between for loop and Enhanced for loop in Java

Last Updated : 10 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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 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);

}

}

 



Similar Reads

String Array with Enhanced For Loop in Java
Enhanced for loop(for-each 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 arrays or collections. This loop also makes the code more readable and r
1 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Difference between for and do-while loop in C, C++, Java
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization condition; testing condition; increment/decrement) { statement(s) } Flow
2 min read
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let's understand the basic differences between a for loop and a while loop. for Loop A for loop provides a concise way of writing the loop structure.
5 min read
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; int main() { int i =
2 min read
Difference between Sentinel and Counter Controlled Loop in C
Sentinel Controlled Loop A sentinel controlled loop is also called an indefinite repetition loop because the number of iterations is not known before the loop starts executing. In a sentinel controlled loop, a special value called sentinel value is used to change the loop control expression from true to false in order to determine whether to execut
3 min read
Difference between Nested Loop Join and Hash Join
1. Nested Loop Join : This is a type of physical join algorithm that is used in case of joining 2 relations. This join is an internal join technique, meaning that we cannot see the join. This is the simplest of all types of joins. This is the best-suited algorithm for small data and smaller transactions. In the case of 2 relations named R and S, th
3 min read
Difference between Nested Loop join and Sort Merge Join
1. Nested Loop Join : Nested Loop Join is the simplest join algorithm which usually has better performance than all other types of joins due to a lesser number of comparisons involved in it. Each row in the outer table is compared to each row in the inner table. The Nested Loop Join algorithm for 2 relations R and S : For each record x of R read in
3 min read
What is the difference between for and Foreach loop in PHP ?
Loops can be used to iterate over collection objects in PHP. The for and foreach loop can be used to iterate over the elements. for loopThe for loop works at the end of the given condition. It is used for the implementation of variables and works in a single way. The for loop does not work in the case of associative arrays. A for loop basically con
3 min read
Difference between forEach() and map() loop in JavaScript
When we work with an array, it is an essential step to iterate on the array to access elements and perform some kind of functionality on those elements to accomplish any task. For this loops like ForEach() and Map() are used. In this article, we are going to learn the difference between the forEach() and map() loops in JavaScript. JavaScript forEac
3 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this article, the difference between these two IO pack
3 min read
Difference between Java and Core Java
Java is a very famous language that is based on the object-oriented programming concepts. It is the successor of the C and C++ languages. It was developed by Sun Microsystems. Core Java is a term used by Sun Microsystems to refer to the Java to standard edition J2SE. This is the parent of all other editions of Java used on internet sites. It has a
2 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with examples and also the difference between these two packag
2 min read
Difference between Core Java and Advanced Java
Java is a versatile and widely used programming language that helps in the development of many software applications. It is popular for its portability, robustness, and ease of use, making it a preferred choice for both beginners and experienced developers. Java's ecosystem can be largely categorized into two main parts that are Core Java and Advan
4 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Syntax: do { // Loop Body Update_expression } // Condition check while (test_expression); Note: The
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number o
4 min read
For-each loop in Java
Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by
4 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i &lt;= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
6 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Difference between Difference Engine and Analytical Engine
Introduction: The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some sim
7 min read