← Back to Chapters

Java do-while Loop

? Java do-while Loop

? Quick Overview

The do-while loop in Java is a control structure that executes a block of code at least once, even if the condition is false.

? Key Concepts

  • Condition is checked after the loop body
  • Loop runs at least one time
  • Ends with a semicolon ;
  • Useful for menu-driven programs

? Syntax / Theory

? View Code Example
// General syntax of do-while loop in Java
do {
    // statements
} while (condition);

? Code Example

? View Code Example
// Java program demonstrating do-while loop
class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;

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

? Live Output / Explanation

Output

The program prints numbers from 1 to 5. The loop executes once before checking the condition, then repeats while the condition remains true.

?️ Interactive Simulator

Modify the values below to simulate how the Java code executes.
Code Logic: do { print(i); i++; } while (i <= Limit);

// Output log will appear here...

✅ Tips & Best Practices

  • Always ensure the condition will eventually become false
  • Use do-while when at least one execution is required
  • Prefer readable conditions to avoid infinite loops

? Try It Yourself

  • Print numbers from 10 to 1 using do-while
  • Create a menu-based program that runs at least once
  • Convert a while loop into a do-while loop