Skip to content

For Loops

In Java, loops allow us to repeat blocks of code. Let’s break down the structure of a for loop:

    public static void main(String[] args) {
        for(int i = 0; i < 5; i++){
            System.out.println("Hello This is my message " + (i + 1));
        }
    }

The ‘for’ loop has three conditions set as parameters within our ( ) brackets and separated by semicolons ; .

  1. Initialisation int i = 0 First we are declaring a variable initialised to zero, This variable will be the count of iterations occurring in our for loop.

  2. Condition i < 5 Here we are telling our for loop to iterate while our i variable is less then five. The condition is evaluated before each iteration of the loop. The loop will continue to run whilst this condition is true.

  3. Increment i++ After each iteration the loop will execute this statement, here we are telling our for loop to increment i by 1 using an augmented assignment operator.

As the loop runs, the statement System.out.println("Hello, This is my message " + (i + 1)); will execute. Notice that we are adding 1 to i inside the println() method. This means the output will display the numbers 1 through 5, rather than starting from 0 this is because the increment of our condition is executed after our value is evaluated.

Output:

Terminal window
Hello, This is my message 1
Hello, This is my message 2
Hello, This is my message 3
Hello, This is my message 4
Hello, This is my message 5
  • The variable i starts at 0, but we add 1 inside the println() statement to display the numbers from 1 to 5 in the output.
  • The loop condition (i < 5) ensures the loop stops after 5 iterations, and the increment (i++) progresses the variable i by 1 each time.