← Back to Home

do-while Loop

The do-while loop in Java is a control flow statement that executes a block of code at least once, and then repeats execution as long as a given condition remains true. This loop is best used when the code must run at least one time, regardless of the condition.

What Is a do-while Loop?

  • Executes loop body before checking the condition
  • Condition is evaluated after each iteration
  • Loop executes at least once

Basic Syntax

do {
    // code to execute
} while (condition);
          

⚠️ Semicolon is mandatory after while(condition);

Simple Example

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

Output:

1
2
3
4
5
          

Guaranteed One-Time Execution Example

int x = 10;
do {
    System.out.println("Executed once");
} while (x < 5);
          

Why it matters: Condition is false, but code executes once.

Execution Flow of do-while Loop

  1. Loop body executes
  2. Condition is checked
  3. If condition is true, loop repeats
  4. If condition is false, loop exits

do-while with break

do {
    if (conditionMet) {
        break;
    }
} while (true);
          

do-while with continue

int i = 0;
do {
    i++;
    if (i == 3) {
        continue;
    }
    System.out.println(i);
} while (i <= 5);
          

Nested do-while Loop

int i = 1;
do {
    int j = 1;
    do {
        System.out.println(i + "," + j);
        j++;
    } while (j <= 2);
    i++;
} while (i <= 3);
          

Common Use Cases

  • Menu-driven programs
  • Input validation
  • User interaction loops
  • Retry mechanisms

do-while vs while

Feature do-while while
Condition Check After loop body Before loop body
Minimum Execution Once Zero or more
Semicolon Required Not required

Common Beginner Mistakes

  • Forgetting semicolon after while()
  • Infinite loops due to missing updates
  • Confusing do-while with while
  • Overusing nested loops

Interview-Ready Answers

Short Answer

The do-while loop executes the loop body at least once and then repeats as long as the condition is true.

Detailed Answer

In Java, the do-while loop checks the condition after executing the loop body, ensuring at least one execution. It is commonly used in menu-driven and user-interaction programs.

Key Takeaway

The do-while loop guarantees at least one execution, making it ideal for interactive and retry-based logic.