DEV Community

Irza Hashim
Irza Hashim

Posted on

A Beginner's Guide to For Loops in Java

Looping is a core concept in computer science. If you need to repeat a task multiple times, you use a loop. In this short tutorial, we will learn exactly how a Java for loop works using a simple code example.

The Code Example

Here is a basic Java loop that prints a message five times:

for (int i = 0; i < 5; i++) {
    System.out.println("The value of i is: " + i);
}
Enter fullscreen mode Exit fullscreen mode

How the Code Works Step-by-Step

A for loop has three main parts inside the parentheses, separated by semicolons:

  • int i = 0; (Initialization): This creates a counter variable named i and sets it to 0. It only runs once when the loop starts.
  • i < 5; (Condition): The loop checks this condition before every single run. If i is less than 5, the loop runs. If i becomes 5, the loop stops immediately.
  • i++ (Increment): This adds 1 to the counter variable i at the end of every loop cycle.

The Output

When you run this Java program, the computer will print this exact output on your screen:

The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)