while Loops

Loops repeat code. A while loop keeps running as long as a condition stays true — perfect when you don't know in advance how many repetitions you need: reading input until it's valid, retrying a download, or waiting until a value is reached.

while

JAVA
void main() {
    int countdown = 3;
    while (countdown > 0) {
        System.out.println(countdown);
        countdown--;
    }
    System.out.println("Lift off!");
}
Output
3
2
1
Lift off!

The condition is checked before each repetition. Something inside the loop must eventually make it false — here countdown--.

Infinite loops

JAVA
int i = 0;
while (i < 10) {
    System.out.println(i);
    // forgot i++ — this prints 0 forever
}

If the condition never becomes false, the loop runs forever. Press Ctrl+C in the terminal to stop a runaway program. Some loops are infinite on purpose, like while (true) in a server — they exit with break or return.

Unknown number of steps

JAVA
void main() {
    double balance = 1000;
    int years = 0;
    while (balance < 2000) {
        balance *= 1.05;
        years++;
    }
    System.out.println("Doubled after " + years + " years: " + "%.2f".formatted(balance));
}
Output
Doubled after 15 years: 2078.93

You couldn't easily know the number of years beforehand — this is where while shines.

do…while

JAVA
void main() {
    int n = 10;
    do {
        System.out.println("Runs at least once: n = " + n);
        n++;
    } while (n < 5);
}
Output
Runs at least once: n = 10

A do…while loop checks its condition after the body, so the body always runs at least once. It's natural for menus and input prompts: show the prompt, then decide whether to repeat.

Processing digits

JAVA
void main() {
    int number = 90417;
    int sum = 0;
    int digits = 0;
    while (number > 0) {
        sum += number % 10;
        number /= 10;
        digits++;
    }
    System.out.println(digits + " digits, sum " + sum);
}
Output
5 digits, sum 21

A menu loop

JAVA
import java.util.Scanner;

void main() {
    Scanner in = new Scanner(System.in);
    String choice;
    do {
        System.out.println("1) Say hello  2) Show time  q) Quit");
        choice = in.nextLine();
        switch (choice) {
            case "1" -> System.out.println("Hello!");
            case "2" -> System.out.println("It's coffee time.");
            case "q" -> System.out.println("Bye");
            default -> System.out.println("Unknown option");
        }
    } while (!choice.equals("q"));
}
Input
1
x
q
Output
1) Say hello  2) Show time  q) Quit
Hello!
1) Say hello  2) Show time  q) Quit
Unknown option
1) Say hello  2) Show time  q) Quit
Bye

Try it yourself

The Collatz sequence: if n is even, halve it; if odd, triple it and add one. Count the steps to reach 1.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Output
Steps: 111, highest value: 9232