DEV Community

MOHAMED ABDULLAH
MOHAMED ABDULLAH

Posted on

while Loop in Java

What is a while Loop?

A while loop is used to repeat a block of code as long as a specified condition is true. It checks the condition before executing the loop body, which makes it an entry-controlled loop.

structure:
initialization; // Step 1

while (condition) { // Step 2
// code block to be executed // Step 3

increment/decrement;  // Step 4
Enter fullscreen mode Exit fullscreen mode

}
public class WhileExample {
public static void main(String[] args) {
int i = 1; // Initialization

    while (i <= 5) { // Condition
        System.out.println(i); // Code block
        i++; // Increment – very important!
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Explanation of the 4 Parts:

Initialization: int i = 1;

Condition: i <= 5

Action (body): System.out.println(i);

Increment/Decrement: i++ (so the loop moves forward)

Without Increment/Decrement – Infinite Loop Danger

int i = 1;

while (i <= 5) {
System.out.println(i); // No increment here
}
This will print 1 forever! Because i never changes, the condition i <= 5 stays true

With Decrement Example – Countdown

int count = 5;

while (count > 0) {
System.out.println("Countdown: " + count);
count--; // Decrement
}

reference link :

1: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Top comments (0)