EMZETT.
Login

do-while Loop

do-while-Schleife Image: Taylor, CC BY-SA 4.0, Wikimedia Commons

In short: The post-test loop form in Java — the body runs once first, and only afterwards is it checked whether it should repeat.

In more detail: Syntactically the condition goes at the end, with a closing semicolon: do { ... } while (condition);. Often used for input validation, since the input prompt has to appear at least once before it can be checked whether it was valid.

int input;
do {
    input = scanner.nextInt();
} while (input < 0);

In Depth

The decisive difference from a normal while loop: a while loop checks the condition BEFORE the first iteration and can therefore run zero times, a do-while loop is guaranteed to run at least once, no matter what the condition looks like at the start:

Scanner scanner = new Scanner(System.in);
int input;
 
do {
    System.out.print("Enter a number between 1 and 10: ");
    input = scanner.nextInt();
    if (input < 1 || input > 10) {
        System.out.println("Invalid, please try again.");
    }
} while (input < 1 || input > 10);
 
System.out.println("Valid input: " + input);

Menu-driven programs are another typical use case: the menu has to be shown at least once before it can even be checked whether the user wants to quit — with a normal while loop, you’d either have to duplicate the menu output before the loop or invent an artificial condition that’s always true the first time. In practice, do-while is significantly rarer in Java code than for and while, because most cases can also be solved with a while(true) { ... if (condition) break; } construct, which some find more readable.

Complete menu example

Scanner scanner = new Scanner(System.in);
int choice;
 
do {
    System.out.println("1) New  2) Open  3) Exit");
    choice = scanner.nextInt();
 
    switch (choice) {
        case 1 -> System.out.println("New file created");
        case 2 -> System.out.println("File opened");
        case 3 -> System.out.println("Exiting program");
        default -> System.out.println("Invalid choice");
    }
} while (choice != 3);

The menu is guaranteed to be shown at least once, even before any input exists at all — exactly the behaviour a while loop can’t offer without an extra trick.

Common syntax error

A classic beginner mistake is forgetting the closing semicolon after the while condition — unlike a normal while loop, it’s mandatory for do-while, since otherwise the condition isn’t syntactically recognised as the end of the do block:

do {
    // ...
} while (condition) // ERROR: missing semicolon, compiler error

Comparison to other languages

Not every language offers a do-while loop — Python, for example, does without it entirely and usually simulates the same behaviour with while True: plus a break at the end of the block. In Java, C, C++, and C#, by contrast, do-while is part of the standard language scope.

See also: Post-Test Loop, While Loop, User Input