Control FlowCore· 25 min read

while Loops

A while loop repeats as long as a condition stays true — great when you do not know the count in advance.

What you will learn

  • Write a while loop
  • Avoid infinite loops
  • Tell when to use while instead of for

Loop until something changes

A for loop is best when you know the number of rounds. A while loop is best when you do not — you just keep going while a condition is true.

A while loop counting down
int countdown = 3;

while (countdown > 0) {
    System.out.println(countdown);
    countdown--;
}
System.out.println("Go!");

Note: Output: 3 2 1 Go! Java checks countdown > 0 before each round. It prints, then countdown-- shrinks the value. When countdown hits 0 the condition is false, so the loop stops and Go! prints.

The golden rule of while

Something inside the loop must eventually make the condition false, or the loop never ends. In the example, countdown-- is what does it.

Watch out: If you forget to change the variable (remove countdown-- above), the condition stays true forever and your program freezes — an infinite loop. If that happens, stop the program with Ctrl + C in the terminal.

A real use: keep asking until valid

Repeat until the user gives a valid answer
import java.util.Scanner;

public class AskAge {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int age = -1;

        while (age < 0) {
            System.out.print("Enter your age (0 or more): ");
            age = input.nextInt();
        }
        System.out.println("Thanks! Age recorded: " + age);
    }
}

Note: Output (user typed -5 then 30): Enter your age (0 or more): -5 Enter your age (0 or more): 30 Thanks! Age recorded: 30 We do not know how many wrong tries the user will make, so a while loop is perfect. It keeps asking while age < 0 and stops once a valid number arrives.

Tip: There is also a do { ... } while (...) loop that always runs at least once before checking the condition. Use it for menus that must show before the first check.

Q. When is a while loop a better choice than a for loop?

Answer: for loops shine when the count is known. while loops shine for an unknown number of rounds — like repeating until the user types valid input.

✍️ Practice

  1. Use a while loop to print the numbers 10 down to 1.
  2. Keep asking the user for a number with Scanner until they type 0, then say Goodbye.

🏠 Homework

  1. Write a program that keeps doubling a number (start at 1) and printing it, while it stays under 100.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →