Difference Between for loop and Enhanced for loop in Java


Java offers numerous choices when it comes to iterating over elements with two popular looping constructs: the traditional and enhanced "for each" loops each offering a distinct approach towards accomplishing this task. Knowing how these mechanisms vary is essential information that will encourage informed decision making among Java programmers regarding which style will be best suited for specific circumstances.

Syntax

The syntax of the traditional for loop is as follows:

for (initialization; condition; increment/decrement) {
   // Code to be executed
}

The enhanced for loop, also known as the "foreach" loop, has a different syntax:

for (datatype variable : collection) {
   // Code to be executed
}

Explanation of Syntax

The conventional for loop consists of three parts: initialization, condition, and increment/decrement. The initialization step is executed as it were once at the starting. The condition is evaluated before each cycle, and on the off chance that it is genuine, the code inside the loop is executed. After each cycle, the increment/decrement step is performed.

On the other hand, the improved for loop simplifies the language structure by eliminating the requirement for initialization, condition, and increment/decrement steps. It directly iterates over a collection or array.

Approach 1: Traditional for loop

Algorithm

  • Initialize a variable.

  • Specify the condition for executing the loop.

  • Execute the code block inside the loop.

  • Increment or decrement the variable.

Example

public class TraditionalForLoopExample {
   public static void main(String[] args) {
      for (int i = 0; i < 5; i++) {
         System.out.println("Iteration: " + i);
      }
   }
}

Output

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Explanation

The code begins with the declaration of a public class named TraditionalForLoopExample

Within the confines of the classroom, one can stumble upon a fundamental procedure known as the main method. Such a component operates as the gateway for said program to commence execution.

The for keyword indicates the start of the loop construct.

int i = 0 initializes a loop control variable i with an initial value of 0.

i < 5 is the condition that determines whether the loop should continue executing. As long as i is less than 5, the loop will continue iterating.

This code employs an iteration statement in order to update an incrementing integer variable named 'i'. In each subsequent cycle through our program loop implementation, we add one (via '++', as mentioned) to whatever present value for 'i' we encounter via our command stream here- allowing us to track current iterators with ease. Contained within a block cited via brackets {}, we have everything that comes under our programmatic umbrella when we talk about 'the loop.' Herein lies a special command - System.out.println("Iteration: " + i); - outputting data comprising both text ("Iteration") and variables on-screen at present when run.

The loop continues to execute until the condition i < 5 becomes false. In this case, when i reaches a value of 5, the condition is no longer true, and the loop terminates.

Approach 2: Enhanced for loop

Algorithm

  • Declare a variable to hold each element of the collection.

  • Specify the collection to be iterated.

  • Execute the code block inside the loop, using the declared variable to access each element.

  • Consider the following example of the enhanced for loop

Example

public class EnhancedForLoopExample {
   public static void main(String[] args) {
      String[] fruits = {"Apple", "Banana", "Orange"};
      for (String fruit : fruits) {
         System.out.println("Fruit: " + fruit);
      }
   }
}

Output

Fruit: Apple
Fruit: Banana
Fruit: Orange

Explanation

The code begins with the declaration of a public class named EnhancedForLoopExample.

Within the confines of the classroom, one can stumble upon a fundamental procedure known as the main method. Such a component operates as the gateway for said program to commence execution.

An array of type String named fruits is declared. This line of code creates an array named fruits that can hold String values. The array is initialized with three elements: "Apple", "Banana", and "Orange".

The enhanced for loop simplifies the process of iterating over arrays and collections.

The loop iterates over each element in the fruits array, assigning the current element to the loop variable fruit.

Executing a code block enclosed within curly braces {} for each iteration allows printing of every individual element from an array of fruits with ease. The output includes both a static label "Fruit:" and a variable value representing one specific item at any moment while iterating through them via System.out.println("Fruit: " + fruit);. This approach eliminates any risks regarding order displacement or index-gaps associated with manual indexing techniques commonly employed to traverse datasets like arrays.

Difference Between for loop and Enhanced for loop in Java

Points of Difference

Traditional for Loop

Enhanced for Loop

Syntax

Requires explicit initialization, condition, and increment/decrement steps

Simplified syntax with no need for initialization, condition, or increment/decrement steps

Iteration Control

Provides more control over initialization, condition, and increment/decrement steps

Automatically iterates over elements of a collection or array

Accessing Elements

Can access elements using an index variable and array/collection size

Directly accesses elements without the need for index or size

Code Readability

Requires explicit handling of iteration details

Enhances code readability by abstracting away iteration details

Use Cases

Suitable for situations where explicit control over iteration is necessary

Ideal for iterating over collections or arrays without complex iteration requirements

Conclusion

Both the traditional for loop and the enhanced for loop have their own significance in Java programming. The conventional for loop gives more adaptability and control over the emphasis handle, permitting the software engineer to characterize the initialization, condition, and increment/decrement steps. It is commonly utilized when the number of cycles or the particular conditions are known in development.

Updated on: 28-Jul-2023

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements