1 min read

Java For Loop

For loops allow you to execute a block of code a fixed number of times.
Java For Loop

What Are For Loops?

A for loop is used when you want to repeatably execute a block of code. They are commonly used with collections or arrays. One use case for a for loop would be displaying reviews for a product. You would execute a block of code for each review to display on the screen.

Syntax

For loops contain three statements. The basic syntax is the following:

for (statement1; statement2; statement3) {
    // code to execute
}

The first statement declares and assigns a variable a value. This is called once before the loop executes.

The second statement is the condition of the loop. This is checked before the loop executes an iteration.

The third statement updates the counter in your loop. This is called after an iteration has completed. An example of a for loop would be the following:

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

This will print the following to the console.

0
1
2
3
4

Be careful when using for loops. It is easy to have an off-by-one error.

Omitting Statements

Each of the statements in a for loop is optional. You could define the variable outside of the loop and omit the variable declaration.

int i = 0;

for (; i < 10; i++) {
    // code to execute
}

You could use an iterator and grab the next element inside of the loop and omit the third statement.

for (Iterator i = users.iterator(); i.hasNext();) {
    final User user = i.next();
    // code to execute
}

You could define an infinite for loop by omitting each statement with the following:

for (;;) {
    // code to execute
}

Conclusion

For loops are best used when you have a fixed number of times you need to execute a block of code. When using for loops, be mindful of off-by-one errors.