← Back to Chapters

Java for-each Loop

? Java for-each Loop

? Quick Overview

The for-each loop in Java is a simplified looping structure used to iterate over arrays and collections without using indexes.

? Key Concepts

  • Introduced in Java 5
  • Also called enhanced for loop
  • Read-only iteration
  • No index handling

? Syntax / Theory

The loop automatically accesses each element in sequence.

? View Code Example
// General syntax of for-each loop
for(dataType variable : collection){
    // statements using variable
}

? Code Example

? View Code Example
// Example of for-each loop with array
class Main {
public static void main(String[] args) {
int[] numbers = {10,20,30,40};
// Loop through each element
for(int num : numbers){
System.out.println(num);
}
}
}

? Live Output / Explanation

Output

10
20
30
40

The loop picks one value at a time from the array and prints it.

? Interactive Simulation

Scenario: Calculate Sum using for-each

int[] data = { 5, 12, 8, 20 };
 
Current num: -
Total Sum: 0

✅ Tips & Best Practices

  • Use when index is not required
  • Improves readability
  • Avoid modifying collection inside loop

? Try It Yourself

  • Use for-each with String array
  • Iterate over ArrayList
  • Print sum of elements