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);
}
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 namediand sets it to 0. It only runs once when the loop starts. -
i < 5;(Condition): The loop checks this condition before every single run. Ifiis less than 5, the loop runs. Ifibecomes 5, the loop stops immediately. -
i++(Increment): This adds 1 to the counter variableiat 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
Top comments (0)