Java:Java While and Do-While Loops with Examples
Java•Loops

Java While and Do-While Loops with Examples

Execute statements repeatedly while a condition evaluates to true in Java.

Syntax

while (condition) {} do {} while (condition);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
whilePre-test LoopChecks condition before body.
do-whilePost-test LoopExecutes body at least once before checking condition.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        int countdown = 3;
        System.out.println("--- Rocket Countdown ---");
        while (countdown > 0) {
            System.out.println("T-minus " + countdown + "...");
            countdown--;
        }
        System.out.println("Liftoff! 🚀\n");

        int attempts = 0;
        do {
            attempts++;
            System.out.println("Handshake attempt: " + attempts);
        } while (attempts < 1);
    }
}
Expected Output:
--- Rocket Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

Handshake attempt: 1

How It Works: Step-by-Step

  • Lines 5-8: Decrements countdown until 0.
  • Lines 12-15: do-while executes block once before evaluating condition.

Key Concepts

  • while checks condition first; if false initially, it does not execute.
  • do-while is guaranteed to execute at least once.
  • Always ensure the condition variable is mutated inside the loop.

Common Mistake: Placing semicolon immediately after while(condition);

while(cond); creates an infinite empty loop because the semicolon terminates the loop statement.

❌ Incorrect
while (x > 0); { x--; } // Infinite loop!
✅ Correct
while (x > 0) { x--; }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler