Home >Java >javaTutorial >What is the difference between for loop and enhanced for loop in Java?

What is the difference between for loop and enhanced for loop in Java?

王林
王林forward
2023-08-19 19:45:261502browse

What is the difference between for loop and enhanced for loop in Java?

Java offers many options when it comes to iterating elements, two of the popular loop constructs are the traditional and enhanced "for each" loops, which each provide different method to accomplish this task. Understanding the differences in these mechanisms is important information for Java programmers to choose the most appropriate style for a given situation.

grammar

The syntax of the traditional for loop is as follows:

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

Enhanced for loops, also known as "foreach" loops, have different syntax:

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

Glossary explanation

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.

The Chinese translation of

Example

is:

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
The Chinese translation of

Explanation

is:

Explanation

The code begins by declaring a public class named TraditionalForLoopExample

Within the confines of the class, one can find a basic process called the main method. This component serves as the entry point for program 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

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 will continue to execute until condition i

Approach 2: Enhanced for loop

Algorithm

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

  • Specify the collection to be iterated.

  • Execute the code block in a loop, accessing each element using the declared variables.

  • Consider the following example of the enhanced for loop

The Chinese translation of

Example

is:

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
The Chinese translation of

Explanation

is:

Explanation

The code begins by declaring a public class called EnhancedForLoopExample.

Within the confines of the class, one can find a basic process called the main method. This component serves as the entry point for program execution.

Declares an array of String type named fruits. This line of code creates an array called fruits that can store 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.

Loop through each element in the fruit array and assign the current element to the loop variable fruit.

For each iteration, execute the block of code enclosed in curly braces {} to easily print out each individual element in the fruits array. The output includes a static label "Fruit:" and a variable value representing any specific item during the current iteration, via System.out.println("Fruit: " fruit);. This approach eliminates the risk of order misalignment or index gaps associated with manual indexing techniques commonly used to traverse data sets such as arrays.

Difference Between for loop and Enhanced for loop in Java

Differences

Traditional for Loop

Enhanced for loop

Syntax

Requires explicit initialization, condition, and increment/decrement steps

Simplified syntax, no initialization, conditions or addition or subtraction steps required

Iteration Control

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

Automatically iterate elements of a collection or array

Accessing elements

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

Direct access to elements, no index or size required

Code readability

Requires explicit handling of iteration details

Improving code readability by abstracting 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.

The above is the detailed content of What is the difference between for loop and enhanced for loop in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete