DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 2: `do-while` Loop

In Part 1, we explored the while loop and learned that it checks its condition before executing the loop body. This means a while loop may execute zero times if the condition is initially false.

But what if you want the loop body to execute at least once, regardless of the condition?

That's exactly what the do-while loop is designed for.

In this article, we'll learn how the do-while loop works, understand its syntax, explore compiler rules, and discuss common interview questions and beginner mistakes.


What Is the do-while Loop?

A do-while loop executes the loop body first, and then checks the condition.

Because the condition is evaluated after the body executes, the loop body always runs at least once.


Syntax

do {

    // loop body

} while (condition);
Enter fullscreen mode Exit fullscreen mode

Notice the semicolon (;) after the while condition.

It is mandatory.


How the do-while Loop Works

The execution flow is:

  1. Execute the loop body.
  2. Evaluate the condition.
  3. If the condition is true, repeat the loop.
  4. Otherwise, exit the loop.

Unlike the while loop, the body is guaranteed to execute once.


Your First do-while Program

int count = 1;

do {

    System.out.println(count);

    count++;

} while (count <= 5);
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Why Use a do-while Loop?

Suppose you want to display a menu to the user.

The menu should appear at least once, even before any input is received.

boolean continueProgram = false;

do {

    System.out.println("Welcome!");

} while (continueProgram);
Enter fullscreen mode Exit fullscreen mode

Output

Welcome!
Enter fullscreen mode Exit fullscreen mode

Even though the condition is false, the body executes once.


while vs do-while

boolean condition = false;
Enter fullscreen mode Exit fullscreen mode

Using while

while (condition) {

    System.out.println("Hello");

}
Enter fullscreen mode Exit fullscreen mode

Output

No output
Enter fullscreen mode Exit fullscreen mode

Using do-while

do {

    System.out.println("Hello");

} while (condition);
Enter fullscreen mode Exit fullscreen mode

Output

Hello
Enter fullscreen mode Exit fullscreen mode

This is the biggest difference between the two loops.


Rule 1: The Condition Must Be boolean

Correct

int count = 1;

do {

    count++;

} while (count <= 5);
Enter fullscreen mode Exit fullscreen mode

Incorrect

do {

} while (1);
Enter fullscreen mode Exit fullscreen mode

Compile-time error

incompatible types:
int cannot be converted to boolean
Enter fullscreen mode Exit fullscreen mode

Java never converts integers into boolean values.


Rule 2: Curly Braces Are Optional

For a single statement, braces may be omitted.

int count = 1;

do

    System.out.println(count++);

while (count <= 3);
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
Enter fullscreen mode Exit fullscreen mode

Although valid, braces improve readability.


Multiple Statements Need Braces

Incorrect

int count = 1;

do

    System.out.println(count);

    count++;

while (count <= 3);
Enter fullscreen mode Exit fullscreen mode

Only the first statement belongs to the loop.

Correct

int count = 1;

do {

    System.out.println(count);

    count++;

} while (count <= 3);
Enter fullscreen mode Exit fullscreen mode

Rule 3: Variable Declarations Need Braces

Incorrect

do

    int number = 10;

while (true);
Enter fullscreen mode Exit fullscreen mode

Compile-time error

variable declaration not allowed here
Enter fullscreen mode Exit fullscreen mode

Correct

do {

    int number = 10;

} while (false);
Enter fullscreen mode Exit fullscreen mode

Rule 4: The Semicolon Is Mandatory

Incorrect

do {

    System.out.println("Hello");

} while (false)
Enter fullscreen mode Exit fullscreen mode

Compile-time error

The compiler expects a semicolon.

Correct

do {

    System.out.println("Hello");

} while (false);
Enter fullscreen mode Exit fullscreen mode

Empty Statement

A semicolon is a valid statement.

do;

while (true);
Enter fullscreen mode Exit fullscreen mode

This is a valid infinite loop with an empty body.

Although legal, it is rarely useful.


Nested do-while

Nested loops are allowed.

int outer = 1;

do {

    int inner = 1;

    do {

        System.out.println(outer + " " + inner);

        inner++;

    } while (inner <= 2);

    outer++;

} while (outer <= 2);
Enter fullscreen mode Exit fullscreen mode

Output

1 1
1 2
2 1
2 2
Enter fullscreen mode Exit fullscreen mode

Unreachable Statement Rule

Java reports an error whenever it knows that some code can never execute.


Case 1

do {

} while (true);

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

The compiler knows the loop never ends.


Case 2

do {

    System.out.println("Hello");

} while (false);

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Output

Hello
Done
Enter fullscreen mode Exit fullscreen mode

This surprises many beginners.

Unlike a while loop, the body executes before checking the condition.


Effect of final

Example

final int start = 10;
final int end = 20;

do {

} while (start < end);

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

Compile-time error

unreachable statement
Enter fullscreen mode Exit fullscreen mode

Why?

The compiler replaces

start < end
Enter fullscreen mode Exit fullscreen mode

with

10 < 20
Enter fullscreen mode Exit fullscreen mode

which becomes

true
Enter fullscreen mode Exit fullscreen mode

The compiler now knows the loop is infinite.


Without final

int start = 10;
int end = 20;

do {

} while (start < end);

System.out.println("Done");
Enter fullscreen mode Exit fullscreen mode

This compiles successfully because the compiler cannot determine the condition during compilation.


Execution Trace

int count = 1;

do {

    System.out.println(count);

    count++;

} while (count <= 3);
Enter fullscreen mode Exit fullscreen mode
Iteration count before Output count after Condition
1 1 1 2 true
2 2 2 3 true
3 3 3 4 false

Common Beginner Mistakes

Forgetting the Semicolon

Incorrect

do {

} while (false)
Enter fullscreen mode Exit fullscreen mode

Always remember the trailing semicolon.


Forgetting to Update the Loop Variable

int count = 1;

do {

    System.out.println(count);

} while (count <= 5);
Enter fullscreen mode Exit fullscreen mode

Result

Infinite loop.


Using Assignment Instead of Comparison

boolean running = false;

do {

} while (running = true);
Enter fullscreen mode Exit fullscreen mode

The assignment returns true, causing an infinite loop.


Using Non-Boolean Conditions

Incorrect

do {

} while (100);
Enter fullscreen mode Exit fullscreen mode

Only boolean expressions are allowed.


Best Practices

  • Use do-while when the body must execute at least once.
  • Always update the loop variable.
  • Prefer braces, even for a single statement.
  • Keep loop conditions simple.
  • Avoid accidental infinite loops.
  • Never forget the mandatory semicolon.

Interview Questions

What is the main difference between while and do-while?

A while loop checks the condition first.

A do-while loop executes the body first.


Can a do-while loop execute zero times?

No.

It always executes at least once.


Is the semicolon mandatory?

Yes.

It is part of the syntax.


Why does do-while(false) execute once?

Because the condition is evaluated after the body executes.


Why can adding final produce an unreachable statement error?

Because the compiler can evaluate the condition at compile time and determine that the loop never exits.


Quick Memory Trick 🧠

Remember DO:

  • D → Do the work first.
  • O → Only then check the condition.

Or simply remember:

"do first, decide later."


while vs do-while

Feature while do-while
Condition checked Before execution After execution
Minimum executions 0 1
Semicolon required No Yes
Best use case Unknown iterations Must execute once

Key Takeaways

  • A do-while loop executes the body before checking the condition.
  • It always executes at least once.
  • The condition must evaluate to a boolean value.
  • The semicolon after while(condition) is mandatory.
  • Curly braces are optional for a single statement but recommended.
  • do-while(false) executes exactly one iteration.
  • final variables may allow the compiler to detect infinite loops and report unreachable statements.
  • Use do-while when at least one execution is required.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)