for Loop in Java: Its Types and Examples

The for loop in Java is used to repeat a block of code a specific number of times. It's one of the most commonly used loops because it combines initialization, condition checking, and updating in a single, compact line.

Standard for Loop Syntax

for (initialization; condition; update) {
    // code to repeat
}

Basic Example

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
// prints 1 2 3 4 5

How the for Loop Works

  • Initialization runs once, before the loop starts
  • The condition is checked before every iteration — the loop runs only while it's true
  • The update statement runs after each iteration, typically incrementing or decrementing a counter

Enhanced for-each Loop

Introduced to simplify iterating over arrays and collections, the for-each loop removes the need for an index variable entirely.

int[] numbers = {10, 20, 30};
for (int num : numbers) {
    System.out.println(num);
}

Nested for Loop

A for loop placed inside another for loop, commonly used for working with grids, matrices, or patterns.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println(i + "-" + j);
    }
}

Infinite for Loop

Leaving all three parts of the for loop empty creates an infinite loop, which must be stopped manually with a break statement.

for (;;) {
    // runs forever unless broken out of
}
Use the standard for loop when you know exactly how many times to repeat something, and switch to the for-each version whenever you're simply iterating over every element of a collection.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course