DEV Community

Kesavarthini
Kesavarthini

Posted on

For Loop and While Loop in Java

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
}
Enter fullscreen mode Exit fullscreen mode

βœ… Example

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
}
Enter fullscreen mode Exit fullscreen mode

βœ… Example

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)