Java:Java For Loops and Enhanced For-Each Loop with Examples
Java•Loops

Java For Loops and Enhanced For-Each Loop with Examples

Learn index-based counting loops and the enhanced for-each loop (for (Type item : collection)).

Syntax

for (int i = 0; i < n; i++) {} for (String item : list) {}

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
for (Type x : collection)Enhanced For LoopIterates through array or Iterable elements cleanly.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        // 1. Classical counter loop
        System.out.println("--- Squares Table ---");
        for (int i = 1; i <= 3; i++) {
            System.out.println(i + " squared = " + (i * i));
        }

        // 2. Enhanced for-each loop over array
        System.out.println("\n--- Cloud Components ---");
        String[] components = {"API Gateway", "JVM Worker", "Redis Cache"};
        for (String comp : components) {
            System.out.println("-> Component: " + comp);
        }
    }
}
Expected Output:
--- Squares Table ---
1 squared = 1
2 squared = 4
3 squared = 9

--- Cloud Components ---
-> Component: API Gateway
-> Component: JVM Worker
-> Component: Redis Cache

How It Works: Step-by-Step

  • Lines 5-7: Counts from 1 to 3 computing squares.
  • Lines 12-14: Enhanced for-each loop visits every element in components array.

Key Concepts

  • Enhanced for-each loops prevent off-by-one boundary errors.
  • Traditional for loops are preferred when the index position is needed.

Common Mistake: Trying to modify array elements inside an enhanced for-each loop

The loop variable in for (int x : arr) is a copy; mutating x does not change the array.

❌ Incorrect
for (int x : arr) { x = x * 2; } // Array remains unchanged!
✅ Correct
for (int i = 0; i < arr.length; i++) { arr[i] *= 2; }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler