0
0
Javaprogramming~5 mins

While loop execution flow in Java

Choose your learning style9 modes available
Introduction

A while loop helps repeat a set of actions as long as a condition is true. It saves time by avoiding writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you want to count or repeat something until a certain number is reached.
When you want to keep checking if a condition is true before doing something.
When you want to process items one by one until there are no more items.
When you want to wait for an event or change before moving on.
Syntax
Java
while (condition) {
    // code to repeat
}

The condition is checked before each loop. If it is true, the code inside runs.

If the condition is false at the start, the code inside the loop does not run at all.

Examples
This prints numbers 0 to 4. The loop runs while count is less than 5.
Java
int count = 0;
while (count < 5) {
    System.out.println(count);
    count++;
}
This loop runs once because keepGoing becomes false inside the loop.
Java
boolean keepGoing = true;
while (keepGoing) {
    // do something
    keepGoing = false; // stop after one run
}
Sample Program

This program prints numbers from 1 to 3. The loop checks if number is less than or equal to 3 before each run.

Java
public class WhileLoopExample {
    public static void main(String[] args) {
        int number = 1;
        while (number <= 3) {
            System.out.println("Number is: " + number);
            number++;
        }
    }
}
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever (infinite loop).

You can use break inside the loop to stop it early if needed.

Summary

A while loop repeats code as long as a condition is true.

The condition is checked before each repetition.

Be careful to change something inside the loop so it stops eventually.