Java While Loop & Do-While Loop Explained

3 minute read

The while loop repeats a block as long as a condition is true. Use it when you don’t know in advance how many iterations you need.


The while Loop

int count = 1;

while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Syntax

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

The condition is checked before each iteration. If it’s false from the start, the body never executes.


The do-while Loop

Executes the body at least once, then checks the condition.

int count = 1;

do {
    System.out.println("Count: " + count);
    count++;
} while (count <= 5);

Key Difference

int x = 10;

// while — body never runs (condition is false)
while (x < 5) {
    System.out.println("while: " + x);
}

// do-while — body runs ONCE even though condition is false
do {
    System.out.println("do-while: " + x);  // prints "do-while: 10"
} while (x < 5);

Use do-while when you need to execute the body at least once — common for menus and input validation.


Input Validation with Do-While

Scanner scanner = new Scanner(System.in);
int number;

do {
    System.out.print("Enter a positive number: ");
    number = scanner.nextInt();
} while (number <= 0);

System.out.println("You entered: " + number);

The loop keeps asking until the user enters a valid number.


Scanner scanner = new Scanner(System.in);
int choice;

do {
    System.out.println("\n--- Menu ---");
    System.out.println("1. Say Hello");
    System.out.println("2. Say Goodbye");
    System.out.println("3. Exit");
    System.out.print("Choice: ");
    choice = scanner.nextInt();

    switch (choice) {
        case 1 -> System.out.println("Hello!");
        case 2 -> System.out.println("Goodbye!");
        case 3 -> System.out.println("Exiting...");
        default -> System.out.println("Invalid choice.");
    }
} while (choice != 3);

Sentinel Value Pattern

Read input until a special value signals to stop:

Scanner scanner = new Scanner(System.in);
int sum = 0;

System.out.println("Enter numbers (-1 to stop):");

int number = scanner.nextInt();
while (number != -1) {
    sum += number;
    number = scanner.nextInt();
}

System.out.println("Sum: " + sum);

Infinite Loops

while (true) {
    // runs forever — use break to exit
}

Controlled Infinite Loop

while (true) {
    System.out.print("Enter 'quit' to exit: ");
    String input = scanner.nextLine();

    if (input.equals("quit")) {
        break;
    }
    System.out.println("You said: " + input);
}

Common Patterns

Countdown

int n = 10;
while (n > 0) {
    System.out.print(n + " ");
    n--;
}
System.out.println("Liftoff!");

Digit Extraction

int number = 12345;
while (number > 0) {
    int digit = number % 10;
    System.out.print(digit + " ");
    number /= 10;
}
// Output: 5 4 3 2 1

GCD (Euclidean Algorithm)

int a = 48, b = 18;
while (b != 0) {
    int temp = b;
    b = a % b;
    a = temp;
}
System.out.println("GCD: " + a);  // 6

Common Mistakes

1. Forgetting to Update the Loop Variable

int i = 0;
while (i < 5) {
    System.out.println(i);
    // OOPS — forgot i++, infinite loop!
}

2. Off-By-One

int i = 1;
while (i < 5) {  // runs 4 times: 1, 2, 3, 4
    i++;
}

while (i <= 5) {  // runs 5 times: 1, 2, 3, 4, 5
    i++;
}

3. Semicolon After While

// Bug — the semicolon makes it an empty loop
while (condition);
{
    // this block is NOT part of the loop
}

While vs For — When to Use Which

Use for Use while
Known number of iterations Unknown iterations
Iterating over a range Waiting for a condition
Array/collection traversal Input validation
Counter-based logic Event-driven logic

Quick Exercises

  1. Write a while loop that prints powers of 2 from 1 to 1024.
  2. Use a do-while loop to ask the user for a password until they enter “secret123”.
  3. Write a program that reverses a number (e.g., 12345 → 54321) using a while loop.

Summary

Loop Checks Condition Minimum Runs
while Before body 0
do-while After body 1

What’s Next?

Sometimes you need to skip an iteration or exit a loop early. That’s what break and continue do: Break and Continue.

Updated: