Web Analytics

For Loops

Beginner ~20 min read

Loops allow you to execute a block of code multiple times. The for loop is commonly used when you know exactly how many times you want to loop.

Standard For Loop

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

The loop has three parts:

  1. Initialization: Runs once before the loop starts (e.g., int i = 0).
  2. Condition: Checked before every iteration. If true, the loop runs. If false, it stops.
  3. Update: Runs after every iteration (e.g., i++).
Java For Loop Lifecycle

Enhanced For-Each Loop

Introduced in Java 5, the "for-each" loop is used exclusively to loop through elements in an array or a collection.

String[] cars = {"Volvo", "BMW", "Ford"};
for (String car : cars) {
    System.out.println(car);
}
Why use it? It's cleaner and less error-prone (no risk of Off-By-One errors with index). Use it whenever you need to read all elements of a collection.
Output
Click Run to execute your code

Nested Loops

Is exactly what it sounds like: a loop inside a loop. This is common when working with 2D arrays (matrices).

// Outer loop
for (int i = 1; i <= 3; i++) {
    // Inner loop
    for (int j = 1; j <= 3; j++) {
        System.out.println(i + " " + j);
    }
}

Summary

  • Use for loops when you know the number of iterations.
  • Use the enhanced for-each loop for iterating over arrays and collections.
  • Be careful with infinite loops (if the condition never becomes false).