while Loop in Java

The while loop in Java repeats a block of code as long as a given condition remains true. Unlike the for loop, it's best suited for situations where the number of iterations isn't known in advance.

Syntax

while (condition) {
    // code to repeat
}

Basic Example

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
// prints 1 2 3 4 5

How the while Loop Works

The condition is checked before each iteration. If it's true, the loop body executes; if it's false right from the start, the loop body never runs at all — this is why while is called an entry-controlled loop.

Using while for Unknown Iteration Counts

The while loop is especially useful when reading input or processing data until a certain condition is met, such as reading lines from a file until the end is reached.

int sum = 0;
int n = 5;
while (n > 0) {
    sum += n;
    n--;
}
System.out.println(sum); // 15

Infinite while Loop

A while loop with a condition that's always true runs forever unless stopped with a break statement inside.

while (true) {
    // runs forever unless broken out of
}
  • while checks its condition before the loop body runs (entry-controlled)
  • Best used when the number of iterations depends on a condition rather than a fixed count
  • Forgetting to update the condition variable inside the loop causes an infinite loop
Always make sure something inside the loop eventually changes the condition — a missing update is one of the most common causes of an accidental infinite loop.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course