Live AI Powered DevOps with AWS
JavaControl flow

Do While Loop

Why Do-While Loop?

In many programs, we sometimes need a loop that executes at least once, regardless of whether the condition is true or false.
This is exactly what the do-while loop is designed for.

Unlike a while loop (which checks the condition before running), the do-while loop runs the body first and then checks the condition.
Because of this structure, the loop body always executes at least once, even if the condition is false initially.

do while loop

Syntax

do {
    // statements
} while (condition);

How it works:

  1. Execute the block inside do { ... }
  2. Check the condition in while (condition)
  3. If condition is true, repeat the loop
  4. If condition is false, stop the loop

Example 1 – Condition False but Runs Once

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

Output

Hi 5

Explanation

  • Even though the condition i <= 4 is false for i = 5,
  • The loop body executes once before the condition is checked.
  • Since the condition becomes false afterward, the loop stops immediately.

This demonstrates the key feature of do-while: first run, then check.

Example 2 – Works Like a While Loop When Condition is True

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

Output

Hi 1
Hi 2
Hi 3
Hi 4

Explanation

  • The condition i <= 4 is true initially, so the loop keeps running.
  • Each iteration prints the value of i and increments it.
  • When i becomes 5, the condition turns false and the loop stops.

In this case, the do-while behaves the same as a regular while loop, but still carries the guarantee of at least one execution.

Key Difference: while vs do-while

Understanding the difference is important because it affects loop behavior.

Featurewhile loopdo-while loop
Condition checkedBefore executionAfter execution
Executes at least 1?Not guaranteedGuaranteed
When to use?When condition may be false initiallyWhen execution should happen once

Simple Explanation

  • while: "Check first, then run"
  • do-while: "Run once, then check"

Summary

  • Use do-while when you want the loop body to run at least once.

  • It is especially useful for tasks like:

    • Input validation
    • Menu-driven programs
    • Reading values until a stop condition
  • A while loop may skip execution entirely, but a do-while loop will not.

Written By: Shiva Srivastava

How is this guide?

Last updated on