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
void main() { int countdown = 3; while (countdown > 0) { System.out.println(countdown); countdown--; } System.out.println("Lift off!"); }
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
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
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)); }
Doubled after 15 years: 2078.93
You couldn't easily know the number of years beforehand — this is where while shines.
do…while
void main() { int n = 10; do { System.out.println("Runs at least once: n = " + n); n++; } while (n < 5); }
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
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); }
5 digits, sum 21
A menu loop
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")); }
1 x q
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.
Steps: 111, highest value: 9232