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:
| Parameter | Type | Description |
|---|---|---|
| while | Pre-test Loop | Checks condition before body. |
| do-while | Post-test Loop | Executes body at least once before checking condition. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java For Loops and Enhanced For-Each Loop with Examples
Master traditional counting for loops and enhanced for-each iteration over arrays and collections.
Java Break and Continue Loop Control Statements
Interrupt or skip loop iterations using break and continue in Java.
Java If...Else and Ternary Conditional Statements
Implement decision-making logic using if, else if, else, and ternary operators.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.