When writing programs in Java, we often need to repeat a set of statements multiple times.
Instead of writing the same code again and again, Java provides loops to make our programs simple and efficient.
In this blog, Iβll explain for loop and while loop in Java with easy examples for beginners.
πΉ What Is a Loop?
A loop is used to execute a block of code repeatedly until a given condition becomes false.
Java provides different looping statements, but the most commonly used ones are:
β’ for loop
β’ while loop
πΉ For Loop in Java
The for loop is a control flow statement used to execute a block of code repeatedly a specific number of times. The replacement of while loop is for loop.
β
Syntax
for (condition) {
// code to be executed
}
β
Example
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
πΉ How the for loop works
1. Initialization runs once
2. Condition is checked
3. If condition is true β code executes
4. Increment/Decrement happens
5. Steps repeat until condition becomes false
πΉ While Loop in Java
The while loop is a control flow statement used to execute a block of code repeatedly a specific number of times.
β
Syntax
while (condition) {
// code to be executed
}
β
Example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
Top comments (0)