Back to Study Material Java

Do While Loop in Java

The do-while loop is a variation of the while loop with one critical difference: the condition is checked at the end of each iteration rather than the begi...

Do While Loop in Java

Guaranteeing at Least One Execution with Do-While

The do-while loop is a variation of the while loop with one critical difference: the condition is checked at the end of each iteration rather than the beginning. This guarantees that the loop body executes at least once, even if the condition is false from the very start. This behavior makes the do-while the right choice when an action must happen before its continuation condition can be meaningfully checked.

The syntax is: do { body } while (condition);. Notice the semicolon after the closing parenthesis — it is required and its absence is a common syntax error. The body executes first, then the condition is evaluated. If the condition is true, the body executes again. This repeats until the condition becomes false.

The canonical example where do-while shines is menu-driven programs. A menu must be displayed to the user at least once before asking whether to continue: do { displayMenu(); int choice = scanner.nextInt(); processChoice(choice); } while (choice != 0);. Using a while loop here would require displaying the menu before the loop and again inside it to avoid code duplication. The do-while handles it naturally.

Another use case is input validation: do { System.out.print("Enter a positive number: "); n = scanner.nextInt(); } while (n <= 0);. The program asks for input at least once, and if the user provides invalid input, it keeps asking. This pattern is cleaner than initializing n to a dummy invalid value just to enter a while loop.

The do-while loop is the least commonly used of the three loop types in Java. Surveys of large Java codebases consistently show it appears far less frequently than for and while loops. However, when the semantics require guaranteed first-iteration execution, it expresses intent more clearly than the equivalent while loop workaround.

Converting a while loop to a do-while is possible when the condition is always true on the first entry. If there is a possibility that the condition might be false before the first iteration, the loops are not interchangeable without adding a surrounding if statement.

Interview tip: Expect the question: "What is the difference between while and do-while?" The one-sentence answer is that while checks the condition before the first iteration (zero or more executions), whereas do-while checks the condition after (one or more executions). Demonstrating with a concrete example where they produce different output will make the answer memorable.