00:00

for Loop in Java – Syntax and Examples

A loop repeats a block of code. The for loop is Java's go-to loop when you know how many times to repeat, or when you count through a range such as the indexes of an array. It keeps the three parts of counting, start, stop and step, together in one line.

This tutorial explains the syntax and flow of the for loop, shows how to loop over arrays and strings, covers nested loops and variations, and lists the mistakes to avoid.

1. Syntax of the for Loop

Syntax
for (initialization; condition; update) {
    // loop body
}
PartRunsTypical example
InitializationOnce, before the loop startsint i = 0
ConditionBefore every iteration; the loop stops when it is falsei < 10
BodyEach time the condition is trueThe statements in { }
UpdateAfter every iterationi++

2. How the Loop Runs

Flowchart of the Java for loop
  1. Run the initialization.
  2. Check the condition. If it is false, leave the loop.
  3. Run the body.
  4. Run the update, then go back to step 2.

If the condition is false at the very start, the body never runs.

3. Basic Examples

ForBasics.java
public class ForBasics {
    public static void main(String[] args) {
        // init; condition; update
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        int sum = 0;
        for (int n = 1; n <= 100; n++) {
            sum += n;
        }
        System.out.println("Sum of 1..100 = " + sum);

        System.out.print("Even numbers counting down: ");
        for (int i = 10; i >= 0; i -= 2) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
Output
1 2 3 4 5 
Sum of 1..100 = 5050
Even numbers counting down: 10 8 6 4 2 0

The update can be anything: i++, i--, i += 2 or even i *= 2.

4. Looping Over Arrays and Strings

Arrays and strings are indexed from 0 to length - 1, which matches the classic loop for (int i = 0; i < arr.length; i++). A for loop with an index is the right choice when you need the position, want to go backwards, or skip elements.

ForWithArrays.java
public class ForWithArrays {
    public static void main(String[] args) {
        int[] temps = {31, 35, 29, 38, 33};

        int max = temps[0];
        for (int i = 1; i < temps.length; i++) {      // valid indexes: 0 .. length - 1
            if (temps[i] > max) max = temps[i];
        }
        System.out.println("Highest temperature: " + max);

        System.out.print("Reversed: ");
        for (int i = temps.length - 1; i >= 0; i--) {
            System.out.print(temps[i] + " ");
        }
        System.out.println();

        String word = "loop";
        for (int i = 0; i < word.length(); i++) {
            System.out.println("char " + i + " = " + word.charAt(i));
        }
    }
}
Output
Highest temperature: 38
Reversed: 33 38 29 35 31 
char 0 = l
char 1 = o
char 2 = o
char 3 = p

Note that arrays use the field length, while strings use the method length(). When you only need each element in order, the for-each loop is simpler.

5. Nested for Loops

A loop inside another loop is a nested loop. The inner loop completes all of its iterations for each iteration of the outer loop, which makes nested loops ideal for tables, grids, matrices and patterns.

NestedFor.java
public class NestedFor {
    public static void main(String[] args) {
        // Multiplication table: the inner loop runs fully for every outer iteration
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= 5; col++) {
                System.out.printf("%4d", row * col);
            }
            System.out.println();
        }

        // A simple triangle pattern
        for (int line = 1; line <= 4; line++) {
            System.out.println("*".repeat(line));
        }
    }
}
Output
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
*
**
***
****

With n outer and m inner iterations, the body runs n × m times, so nested loops over large data can be slow. For more patterns, see Java Pattern Programs.

6. Variations of the for Loop

ForVariations.java
public class ForVariations {
    public static void main(String[] args) {
        // Two variables in one loop
        for (int left = 0, right = 6; left < right; left++, right--) {
            System.out.print("(" + left + "," + right + ") ");
        }
        System.out.println();

        // All three parts are optional: this is an infinite loop ended by break
        int attempts = 0;
        for (;;) {
            attempts++;
            if (attempts == 3) break;
        }
        System.out.println("Stopped after " + attempts + " attempts");

        // The loop variable is not visible after the loop
        int i;
        for (i = 0; i < 4; i++) { }
        System.out.println("i declared outside the loop ends at " + i);

        // Counting with doubles accumulates rounding errors: loop on integers instead
        for (int step = 0; step <= 3; step++) {
            double value = step / 10.0;
            System.out.print(value + " ");
        }
        System.out.println();
    }
}
Output
(0,6) (1,5) (2,4) 
Stopped after 3 attempts
i declared outside the loop ends at 4
0.0 0.1 0.2 0.3
  • Separate several variables with commas in the initialization and update parts (they must share one type).
  • All three parts are optional; for (;;) is an infinite loop that needs break or return to end.
  • A variable declared in the initialization exists only inside the loop. Declare it before the loop if you need its final value.
  • Count with integers and compute decimals from them (step / 10.0); adding 0.1 repeatedly to a double accumulates rounding errors.

7. Controlling the Loop: break and continue

  • break exits the loop immediately. See break statement.
  • continue skips the rest of the current iteration and moves to the update. See continue statement.
  • Labeled break and continue can exit or continue an outer loop from inside a nested loop.

8. for vs while vs do-while vs for-each

LoopBest forChecks condition
forCounting, index-based loops, known number of iterationsBefore each iteration
whileUnknown number of iterations, waiting for a conditionBefore each iteration
do-whileBodies that must run at least once, such as menusAfter each iteration
for-eachReading every element of an array or collectionAutomatically

9. Common Mistakes

  • Off-by-one errors: i <= arr.length reads one element too many and throws ArrayIndexOutOfBoundsException; use i < arr.length.
  • A semicolon after the header: for (int i = 0; i < 5; i++); has an empty body, so the block below runs only once.
  • Infinite loops from a condition that never becomes false, for example i-- instead of i++.
  • Changing the loop variable inside the body, which makes the loop hard to follow.
  • Modifying a collection while looping over it with an index, which shifts elements and skips some.

10. Summary

  • A for loop has initialization, condition and update parts, and runs its body while the condition is true.
  • It is ideal for counting and index-based work on arrays and strings.
  • Nested loops handle tables and grids; their cost multiplies.
  • All header parts are optional; for (;;) is an infinite loop.
  • Watch out for off-by-one errors and stray semicolons.

Related Tutorials

Reference: Oracle Java Tutorials: The for Statement