Loops in Java
What is Loop?
A loop is a piece of code or statement that executes some block of code again and again until the condition is met. There are three main types of loops in Java: for, while, and do-while.
Here’s an overview of each:
for loop:
The for loop is used when you know in advance how many times the loop should run.
for (initialization; condition; update) {
// code to be executed
}
- Initialization: Executed once at the beginning of the loop.
- Condition: Evaluated before each iteration. If it’s true, the loop continues; otherwise, it exits.
- Update: Executed after each iteration.
Example:
for (int i = 0; i < 5; i++) {
System.out.println(“Iteration: “ + i);
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
while loop:
The while loop is used when the number of iterations is not known in advance.
while (condition) {
// code to be executed
}
Example:
Get Manisha Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
int i = 0;
while (i < 5) {
System.out.println(“Iteration: “ + i);
i++;
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
do-while loop:
The do-while loop is similar to the while loop, but the condition is checked after the execution of the loop block. This guarantees that the block will be executed at least once.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println(“Iteration: “ + i);
i++;
} while (i < 5);
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4





