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:
| Parameter | Type | Description |
|---|---|---|
| for (Type x : collection) | Enhanced For Loop | Iterates through array or Iterable elements cleanly. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java While and Do-While Loops with Examples
Learn while loops for conditional iteration and do-while loops for guaranteed first execution.
Java Break and Continue Loop Control Statements
Interrupt or skip loop iterations using break and continue in Java.
Java ArrayList and Arrays: Dynamic Collections vs Fixed Arrays
Master fixed-size arrays and dynamic java.util.ArrayList with add, get, and remove.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.