Java for loop

Summary: in this tutorial, you will learn how to use the Java for loop to execute a block of code a specified number of times.

Introduction to the Java for loop

Both while and do while loops allow you to execute a block of code as long as a condition is true. They control the number of iterations by the condition. In other words, you don’t know and don’t need to know the number of iterations upfront.

Sometimes, you want to execute a block of code for a specified number of times. To do that, you can use a for loop.

The basic syntax of the for loop in Java is as follows:

for (initialization; condition; update) {
    // Code to be executed
}Code language: Java (java)

The for loop has three main parts:

  • Initialization: This is where you can initialize the loop control variables. The for loop executes the initialization once before the loop starts.
  • Condition: It’s a boolean expression that determines whether the loop should continue or not. If the condition evaluates to true, the loop continues; otherwise, the loop exits. The condition is checked before each iteration.
  • Update: This is where you update the loop control variable after each iteration. It is executed after each iteration and before the condition is checked again.

Technically, the initialization, condition, and update parts are optional. So you can write a for loop like this:

for(;;) {
  // Code to be executed
}Code language: Java (java)

In this case, you need to use an if statement with the break statement to exit the loop conditionally.

Also, the body part is optional:

for (initialization; condition; update);

In practice, you’ll use a for loop to iterate over arrays, collections, or performing tasks with a known number of iterations.

Java for loop examples

Let’s take some examples of using Java for loop.

1) Using a for loop to count from 1 to 5

The following example uses the for loop to display integer numbers from 1 to 5:

public class App {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}Code language: Java (java)

Output:

1
2
3
4
5Code language: Java (java)

In this example:

  • Initialization: int i = 1 that initializes i to 1.
  • Condition: i <= 5 checks if is less than or equal to 5.
  • Update: i++ increment i by 1 after each iteration.

2) Using a for loop to count down from 5 to 1

The following example uses a for loop to count down from 5 to 1:

public class App {
    public static void main(String[] args) {
        for (int i = 5; i >= 1; i--) {
            System.out.println(i);
        }
    }
}Code language: Java (java)

Output:

5
4
3
2
1Code language: Java (java)

In this example:

  • Initialization: int i = 5 that initializes i to 5 once.
  • Condition: i >= 5 checks if is greater than or equal to 5 after each iteration.
  • Update: i-- decreases i by 1 after each iteration.

3) Using for loop to calculate the sum of all integers

The following example shows how to use a for loop to calculate the sum of integers from 1 to 100:

public class App {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 100; i++) {
            total += i;
        }
        System.out.println(total);
    }
}Code language: Java (java)

Output:

5050

Technically, the body of the for loop is optional. Also, the update part of the for loop can have multiple expressions separated by a comma.

Therefore, you can move the total to the update part and remove the entire loop body as follows:

public class App {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 100; i++, total+=i);
        System.out.println(total);
    }
}Code language: Java (java)

It returns the same output.

Nested for loops

Java allows you to nest for loop to create more complex iteration patterns. For example:

public class App {
    public static void main(String[] args) {
       for(int row = 0; row < 3; row++){
           for(int column=0; column < 3; column++){
               System.out.println("(row=" + row + ",column=" + column + ")");
           }
        }
    }
}Code language: Java (java)

Output:

(row=0,column=0)
(row=0,column=1)
(row=0,column=2)
(row=1,column=0)
(row=1,column=1)
(row=1,column=2)
(row=2,column=0)
(row=2,column=1)
(row=2,column=2)Code language: plaintext (plaintext)

In this example, we have two loops: outer and inner loops.

  • The outer loop initializes the row variable to 0 and continues as long as the row is less than 3.
  • The inner loop initializes the column variable to 0 and also continues as long as the column is less than 3.
  • For each iteration of the outer loop, the inner loop runs three iterations. For example, if the row is 0, the column will be 0, 1, and 2.
  • Both outer and inner loops run three iterations, so we have 3×3 = 9 iterations.

Summary

  • Use a Java for loop to execute a block of code for a specified number of times.
Was this tutorial helpful ?