W3docs

Java while Loop

Repeat code in Java with the while loop, including condition checking and infinite loops.

The while loop is the simplest way to repeat a block of code in Java. As long as its condition is true, the body runs again. When the condition becomes false, the loop exits and execution continues after the loop.

Syntax

while (condition) {
  // body — runs while condition is true
}

A minimal example — count from 1 to 5:

int i = 1;
while (i <= 5) {
  System.out.println(i);
  i++;
}

The condition i <= 5 is checked before every iteration. When i becomes 6, the condition is false and the loop ends.

The two parts you must remember

Every while loop needs two things to terminate:

  1. A condition that can become false. A constant true runs forever.
  2. Something inside the body that changes the condition. Forget to update i and the loop is infinite.

A common beginner mistake:

int i = 1;
while (i <= 5) {
  System.out.println(i);
  // forgot i++ — loop runs forever
}

If your program hangs, look here first.

The condition is checked first

If the condition is false at the start, the body never runs at all — not even once:

int i = 10;
while (i < 5) {
  System.out.println(i);   // never executes
}

That's the key difference from the do/while loop, which always runs the body at least once.

When while is the right choice

A for loop is better when you know the count up front (for (int i = 0; i < 10; i++)). A while loop is better when the stopping condition isn't tied to a counter — it's tied to some state changing.

Reading until end of input:

import java.util.Scanner;

Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
  String line = s.nextLine();
  System.out.println("got: " + line);
}

Retrying until success:

boolean connected = false;
int attempts = 0;
while (!connected && attempts < 5) {
  connected = tryConnect();
  attempts++;
}

Processing a queue:

while (!queue.isEmpty()) {
  Task t = queue.poll();
  t.run();
}

Infinite loops on purpose

Sometimes you want the loop to run forever — typically in event loops, servers, or simulations — and you exit with a break:

while (true) {
  String input = readCommand();
  if (input.equals("quit")) {
    break;
  }
  handle(input);
}

while (true) is more idiomatic than while (1 == 1) or other tricks.

Using break and continue

Inside any loop you can use:

  • break — exit the loop entirely
  • continue — skip the rest of the current iteration and re-check the condition

Both are covered in detail in break and continue.

A worked example

java— editable, runs on the server

What's next

A close cousin of while is the do-while loop, which always runs the body at least once.

Practice

Practice

How many times will this loop print? int i = 5; while (i < 5) { System.out.println(i); i++; }