For-each loop in Java

โšก Smart Summary

For-each loop in Java is a simplified form of the for loop used to traverse arrays and lists without a counter or index. This resource explains the for-each syntax, compares it with the traditional for loop, and shows a complete working example with expected output.

  • ๐Ÿ” Purpose: The for-each loop iterates over every element of an array or list directly, reducing code.
  • ๐Ÿงฎ No Counter: Unlike a traditional for loop, for-each needs no index, condition, or increment.
  • ๐Ÿงฉ Syntax: Declare a temporary variable whose type matches the collection, then the collection to iterate.
  • โš–๏ธ Comparison: The example shows the same output from a counter-based loop and a for-each loop.
  • โš ๏ธ Limitation: The for-each loop gives no index, so it cannot easily modify the underlying elements.

For-each loop in Java

Java For-Each Array

The For-Each Loop is another form of for loop used to traverse the array. The for-each loop reduces the code significantly, and there is no use of the index, or rather the counter, in the loop.

Syntax:

for (<DataType of array/List> <Temp variable name> : <Array/List to be iterated>) {
    System.out.println();
    // Any other operation can be done with this temp variable.
}

Loop/Iterate an array in Java

Let us take the example using a String array that you want to iterate over without using any counters. Consider a String array arrData initialized as follows:

String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};

Although you might know methods like finding the size of the array and then iterating through each element of the array using the traditional for loop (counter, condition, and increment), we need a more optimized approach that will not use any such counter.

This is the conventional approach of the “for” loop:

for (int i = 0; i < arrData.length; i++) {
    System.out.println(arrData[i]);
}

You can see the use of the counter and then its use as the index for the array. Java provides a way to use the “for” loop that will iterate through each element of the array.

Here is the code for the array that we declared earlier:

for (String strTemp : arrData) {
    System.out.println(strTemp);
}

You can see the difference between the loops. The code has reduced significantly. Also, there is no use of the index, or rather the counter, in the loop. Do ensure that the data type declared in the for-each loop matches the data type of the ArrayList that you are iterating.

For each loop Example

Here we have the entire class showing the above explanation:

class UsingForEach {
  public static void main(String[] args) {
    String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};
    //The conventional approach of using the for loop
    System.out.println("Using conventional For Loop:");
    for(int i=0; i< arrData.length; i++){
      System.out.println(arrData[i]);
    }
    System.out.println("\nUsing Foreach loop:");
    //The optimized method of using the for loop - also called the foreach loop
    for (String strTemp : arrData){
      System.out.println(strTemp);
    }
  }
}

Iterate an array in Java

Expected Output:

Using conventional For Loop:
Alpha
Beta
Gamma
Delta
Sigma

Using Foreach loop:
Alpha
Beta
Gamma
Delta
Sigma

FAQs

Yes. AI assistants can refactor index-based loops into for-each loops where the index is not needed. You should still review cases that rely on the index for position or element modification.

AI tools often suggest the for-each loop for readability when the index is unused, while keeping indexed loops where the element position or modification matters. The choice depends on the specific task.

A traditional for loop uses a counter and index to control iteration. The for-each loop iterates each element directly without a counter, improving readability but providing no index for element access.

Changing the loop variable does not update the underlying array element, because it holds a copy of the value. To modify elements in place, use a traditional for loop with an index.

Summarize this post with: