Coding

For Loop in Java: Syntax, Examples and the Enhanced For

A for loop in Java repeats a block of code a set number of times: for (int i = 0; i < 5; i++) { ... } runs the body five times, with i going from 0 to 4. Java also has an enhanced for loop, for (int n : numbers), which visits every element of an array or collection without a counter.

for (int i = 0; i < 5; i++) {
    System.out.println("Count is: " + i);
}

Example output: Count is: 0 up to Count is: 4, one line each.

Java for loop syntax

The basic for statement has three expressions in the parentheses, separated by semicolons, followed by the statement or block to repeat. The Java Tutorials give the general form as:

for (initialization; termination; increment) {
    statement(s)
}
PartWhen it runsTypical use
initializationonce, as the loop beginsint i = 0
termination (the condition)before each iteration; the loop ends when it is falsei < 5
increment (the update)after each iteration of the bodyi++ or i--

The Java Language Specification adds that the condition must be of type boolean or Boolean, or you get a compile-time error. Unlike C, an int such as 1 does not count as true. The update can be any statement expression, so i += 2 is fine, and the tutorial notes that it is just as acceptable to decrement as to increment.

A variable declared in the initialization part is scoped to the loop. Oracle's tutorial puts it this way: its scope extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions too. After the closing brace, i no longer exists. The tutorial recommends this style when you do not need the counter afterwards, because it limits the variable's life span and reduces errors.

Common for loop examples in Java

Loop through an array by index

Start at 0 and stop before array.length. The last valid index is length - 1, so use < and not <=. With <= the final pass reads past the end of the array, the classic off-by-one bug.

String[] fruits = {"apple", "banana", "cherry"};

for (int i = 0; i < fruits.length; i++) {
    System.out.println(i + " " + fruits[i]);
}

Example output:

0 apple
1 banana
2 cherry

Note that length on an array is a field, with no parentheses. For a List you would call size() instead.

Count down

Start high, test against a lower bound and decrement:

for (int i = 3; i > 0; i--) {
    System.out.println(i);
}
System.out.println("liftoff");

Example output: 3, 2, 1, then liftoff.

Step by more than one

for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);
}

Example output: 0 2 4 6 8 10, one per line.

Sum numbers

Declare the accumulator before the loop. A variable declared inside the body is created anew on every pass and is gone when the loop ends.

double[] prices = {4.5, 10, 2.25};
double total = 0;

for (int i = 0; i < prices.length; i++) {
    total += prices[i];
}
System.out.println(total);

Example output: 16.75.

Two variables at once

The initialization part can declare several variables of the same type, and the update can hold several expressions separated by commas. The specification says update expressions are evaluated in sequence from left to right. This walks from both ends of an array toward the middle:

int[] values = {1, 2, 3, 4, 5};

for (int left = 0, right = values.length - 1; left < right; left++, right--) {
    System.out.println(values[left] + " and " + values[right]);
}

Example output: 1 and 5, then 2 and 4. The loop stops when the two indexes meet at 3.

Nested loops

The inner loop runs completely for every pass of the outer one, so a 3 by 3 table runs the inner body 9 times:

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        System.out.print(row * col + " ");
    }
    System.out.println();
}

Example output:

1 2 3
2 4 6
3 6 9 

The enhanced for loop (for-each)

When you want the elements and not the index, use the enhanced for statement. The Java Tutorials show it with an array and recommend it over the general form "whenever possible":

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int item : numbers) {
    System.out.println("Count is: " + item);
}

It also works on collections. Per the specification, the expression after the colon must be an array type or a subtype of Iterable, which covers List, Set and similar types, or you get a compile-time error. On each iteration the local variable is initialized to the next element.

import java.util.List;

List<String> names = List.of("Ada", "Grace", "Linus");

for (String name : names) {
    System.out.println(name);
}

Two limits to know. There is no index, so if you need the position, use the basic loop. And the loop variable is a copy of the element for primitives and a copy of the reference for objects, so assigning to it does not store anything back into the array. Use array[i] = ... in a basic loop to change elements.

java.util.Map is not an Iterable, so you cannot write for (x : map). Loop over map.entrySet(), map.keySet() or map.values(), each of which is a collection you can iterate.

break, continue and labels

An unlabeled break ends the innermost switch, for, while or do-while statement. An unlabeled continue skips to the end of the innermost loop body. In a basic for loop, the specification says the update part then runs and the next iteration step begins.

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;   // skip even numbers
    if (i > 7) break;           // stop entirely after 7
    System.out.println(i);
}

Example output: 1 3 5 7, one per line.

To leave an outer loop from inside an inner one, label the outer loop and name the label in the break. The Java Tutorials' example searches a two-dimensional array this way:

int[][] grid = { {1, 2, 3}, {4, 5, 6} };
int searchFor = 5;
boolean foundIt = false;
int i, j = 0;

search:
for (i = 0; i < grid.length; i++) {
    for (j = 0; j < grid[i].length; j++) {
        if (grid[i][j] == searchFor) {
            foundIt = true;
            break search;
        }
    }
}
System.out.println(foundIt + " at " + i + ", " + j);

Example output: true at 1, 1. Oracle clarifies that break search terminates the labeled statement and does not jump to the label: control continues at the statement right after the labeled loop. A labeled continue works the other way, skipping the current iteration of the outer loop and moving on to its next one. Here i and j are declared outside the loops so the println can still read them.

Infinite loops and the stray semicolon

All three expressions are optional. The Java Tutorials show for ( ; ; ) as the way to write an infinite loop, and the specification states that without a condition the only way the loop can complete normally is a break. That is a legitimate pattern for a loop that reads input until it sees an end marker, as long as the body has a reachable exit:

for (;;) {
    if (done()) break;   // the only normal exit
    work();
}

Accidental infinite loops are usually one of two bugs. The first is a counter that never moves toward the condition, such as i-- in a loop that tests i < 10 and starts at 0. The second is a semicolon straight after the closing parenthesis:

for (int i = 0; i < 3; i++);   // empty statement is the loop body
{
    System.out.println("runs once");
}

The semicolon is an empty statement, which becomes the whole loop body. The loop spins three times doing nothing, and the block below it runs once. Most IDEs and linters flag this.

Which loop should you use?

You wantUse
to count, or step by a custom amountbasic for
every element of an array or a Listenhanced for
the index and the elementbasic for
to modify array elements in placebasic for with array[i] = ...
to loop with no fixed count, until a condition changeswhile or do-while
to stop early or skip itemsany for form with break or continue

If you only use the condition and leave out the other two parts, a while loop says the same thing more plainly.

Coming from JavaScript?

The basic loop looks almost identical in Java and JavaScript, but the types differ: Java requires a declared type such as int and a strictly boolean condition. The two languages are unrelated beyond some shared syntax; Java vs JavaScript covers the differences. For the JavaScript side of loops, see JavaScript for loop: syntax and examples.

Frequently asked questions

Can a Java for loop have no condition?
Yes. All three expressions are optional, and the Java Tutorials show for ( ; ; ) as an infinite loop. The Java Language Specification says that when the condition is absent, the only way the for statement can complete normally is a break statement.
What is the difference between a for loop and a for-each loop in Java?
The basic for loop uses an initialization, a condition and an update, so you control the counter and can step by any amount. The enhanced for (for-each) loop, written for (Type item : collection), hands you each element of an array or Iterable in turn and has no index. Oracle recommends the enhanced form whenever it is enough.
Is the loop variable available after a Java for loop ends?
Not if you declared it in the initialization part. Its scope runs from its declaration to the end of the block governed by the for statement. Declare the variable before the loop if you need its final value afterwards.
Can I use continue inside a for loop in Java?
Yes. In a basic for loop, continue skips the rest of the current iteration, runs the update expression, and then checks the condition again. A labeled continue does the same for an outer loop.

Sources