W3docs

Java do...while Loop

Use the do...while loop in Java to execute a block at least once before checking the condition.

The do/while loop is while's mirror image: it runs the body first, then checks the condition. The result is a loop guaranteed to execute at least once — even if the condition was false from the start.

Syntax

do {
  // body — runs at least once
} while (condition);

Notice the trailing semicolon after while (condition) — easy to miss, and the compiler will tell you if you do.

A direct counterpart to the while counter example:

int i = 1;
do {
  System.out.println(i);
  i++;
} while (i <= 5);

Output: 1 2 3 4 5 — same as the while version, but the body always runs first.

When the condition starts false

This is where do/while differs from while:

int i = 10;
do {
  System.out.println(i);   // prints 10 once
  i++;
} while (i < 5);

The body runs once, then the condition 10 < 5 is false, and the loop exits. A plain while would have skipped the body entirely.

When to use do/while

The classic use case is input validation — you must read the input first to know whether it's valid:

import java.util.Scanner;

Scanner s = new Scanner(System.in);
int n;
do {
  System.out.print("Enter a positive number: ");
  n = s.nextInt();
} while (n <= 0);

Another natural fit is menu loops — you always want to show the menu once:

int choice;
do {
  showMenu();
  choice = readChoice();
  handle(choice);
} while (choice != 0);

In both cases, expressing the loop with plain while would mean duplicating the first iteration's work outside the loop, or using a sentinel variable. do/while is cleaner.

A note on scope

A variable declared inside the body is not visible to the while condition:

do {
  int x = readValue();
} while (x > 0);   // compile error: x not in scope

Declare it outside:

int x;
do {
  x = readValue();
} while (x > 0);

How often you'll actually use it

In practice, do/while is the least-used of Java's three loops. Most loops know whether to run before the first iteration, so while and for cover them. But when "run once then maybe again" is the natural description, do/while is the cleanest expression.

A worked example

java— editable, runs on the server

What's next

The most common Java loop is the for loop, which bundles a counter, condition, and update step into one tidy header.

Practice

Practice

How many times does this loop run? int i = 10; do { System.out.println(i); i++; } while (i < 5);