🌱BeginnerLoops

do-while Loop

Execute code at least once, then repeat while a condition holds - the do-while loop guarantees the first iteration always runs.

Overview

The do-while loop is the only Java loop that guarantees the body runs at least once. Unlike while (condition checked before the body), do-while checks the condition after the body executes. This makes it ideal for menus, input prompts, and any scenario where you need to run the action before knowing whether to repeat it. Syntax: do { ... } while (condition); - note the mandatory semicolon after the closing parenthesis.

Key Points

  • •Body executes AT LEAST ONCE regardless of the condition
  • •Condition is checked AFTER the body, not before
  • •Syntax: do { body } while (condition); - the semicolon after while(...) is required
  • •Useful for menus: show menu → get choice → repeat if invalid
  • •If condition is true after the first run, the body repeats; if false, the loop ends
  • •Can always be rewritten as a while loop, but do-while is more natural for "run then check" patterns

Examples

Basic do-while vs while comparison

public class Main {
    public static void main(String[] args) {
        // while: 0 iterations if condition is false from start
        int x = 10;
        while (x < 5) {
            System.out.println("while: " + x); // never prints
            x++;
        }

        // do-while: always at least 1 iteration
        int y = 10;
        do {
            System.out.println("do-while: " + y); // prints once (10)
            y++;
        } while (y < 5);
    }
}

The do-while prints even though y (10) is not < 5. The while loop does not print at all.

Menu-driven program - classic do-while use case

import java.util.Scanner;

public class Menu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n1. Say Hello");
            System.out.println("2. Say Goodbye");
            System.out.println("3. Exit");
            System.out.print("Choose: ");
            choice = sc.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 option");
            }
        } while (choice != 3);

        sc.close();
    }
}

The menu must show at least once before we can check if the user wants to exit - do-while is perfect.

Input validation with do-while

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age;

        do {
            System.out.print("Enter your age (1-120): ");
            age = sc.nextInt();
        } while (age < 1 || age > 120);

        System.out.println("Your age: " + age);
        sc.close();
    }
}

We must prompt at least once, then re-prompt if the input is invalid - do-while fits naturally.

Common Mistakes

  • Forgetting the semicolon at the end: `} while (condition)` - without the semicolon this is a compile error
  • Confusing with while: do-while always runs at least once; while may run zero times
  • Infinite loop: if the condition in the while clause is always true, the loop runs forever

Note

The do-while is rarer than for and while but shines in two scenarios: interactive menus (show options at least once) and input validation (prompt at least once and re-prompt if invalid). Recognize these patterns and reach for do-while.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

How does do-while differ from while?