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)); } }
Explanation of the For
loop structure
Section titled “Explanation of the For loop structure”The ‘for’ loop has three conditions set as parameters within our (
)
brackets and separated by semicolons ;
.
-
Initialisation
int i = 0
First we are declaring a variable initialised to zero, This variable will be the count of iterations occurring in ourfor
loop. -
Condition
i < 5
Here we are telling our for loop to iterate while ouri
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. -
Increment
i++
After each iteration the loop will execute this statement, here we are telling ourfor
loop to incrementi
by1
using an augmented assignment operator.
Loop Execution and Output
Section titled “Loop Execution and Output”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:
Hello, This is my message 1Hello, This is my message 2Hello, This is my message 3Hello, This is my message 4Hello, This is my message 5
- The variable
i
starts at 0, but we add 1 inside theprintln()
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 variablei
by 1 each time.