while / do-while (Java)
These are the basic loop constructs in Java. A while loop repeatedly executes its block as long as the condition is true. A do-while loop executes the block first and then evaluates the condition, so the block is guaranteed to run at least once. This page also covers the pattern of using an infinite loop with break to exit.
Syntax
// Basic while loop syntax
// The condition is evaluated first. If it is false from the start, the block never runs
while (condition) {
// Executes repeatedly while condition is true
}
// Basic do-while loop syntax
// The block runs first, then the condition is evaluated. The block always runs at least once
do {
// Always runs at least once, then repeats while condition is true
} while (condition); // Semicolon is required
// Combining an infinite loop with break
// Useful when the exit condition is complex or hard to evaluate upfront
while (true) {
// Loop body
if (exitCondition) {
break; // Exits the loop
}
}
Differences between while and do-while
| Syntax | When the condition is evaluated | Minimum executions | Typical use cases |
|---|---|---|---|
| while | Before the block runs (pre-check) | 0 times (the block never runs if the condition is false from the start) | Loops where the iteration count may be zero. |
| do-while | After the block runs (post-check) | 1 time (the block always runs at least once) | When you need to perform an action first and then decide whether to continue — such as input prompts or menu display. |
Sample Code
WhileBasic.java
public class WhileBasic {
public static void main(String[] args) {
// --- Basic while loop ---
// Itadori Yuji continues fighting until his HP reaches 0
String fighter = "Itadori Yuji";
int hp = 100;
int round = 1;
System.out.println("=== " + fighter + "'s Battle Log ===");
while (hp > 0) {
System.out.println("Round " + round + ": HP = " + hp);
hp -= 35; // Takes 35 damage each round
round++;
}
System.out.println(fighter + " is unable to battle. (Final HP: " + hp + ")");
// --- The block never runs when the condition is false from the start ---
// If HP is already 0 or below, the block is skipped entirely
int defeatedHp = -10;
System.out.println("\n=== Starting with HP=" + defeatedHp + " ===");
while (defeatedHp > 0) {
System.out.println("This message is never printed.");
}
System.out.println("Skipped the while block.");
}
}
javac WhileBasic.java java WhileBasic === Itadori Yuji's Battle Log === Round 1: HP = 100 Round 2: HP = 65 Round 3: HP = 30 Itadori Yuji is unable to battle. (Final HP: -5) === Starting with HP=-10 === Skipped the while block.
DoWhileBasic.java
public class DoWhileBasic {
public static void main(String[] args) {
// --- Basic do-while loop ---
// Gojo Satoru activates his technique. It always activates at least once
String sorcerer = "Gojo Satoru";
int cursedEnergy = 0; // Even with 0 energy, the first activation still occurs
System.out.println("=== " + sorcerer + "'s Technique Activation (do-while) ===");
do {
System.out.println(sorcerer + " activated a technique. (Remaining energy: " + cursedEnergy + ")");
cursedEnergy -= 30; // Consumes 30 energy per activation
} while (cursedEnergy > 0); // Checks remaining energy after each activation
System.out.println("Cursed energy depleted.");
System.out.println();
// --- Comparing while vs do-while behavior ---
// Both start with a condition that is false from the beginning
int energy = 0;
System.out.println("--- while (condition is false from the start) ---");
while (energy > 0) {
System.out.println("This message is never printed.");
}
System.out.println("while block: executed 0 times");
System.out.println("--- do-while (condition is false from the start) ---");
do {
System.out.println("do-while block: always executes at least once.");
} while (energy > 0);
System.out.println("do-while block: executed 1 time");
}
}
javac DoWhileBasic.java java DoWhileBasic === Gojo Satoru's Technique Activation (do-while) === Gojo Satoru activated a technique. (Remaining energy: 0) Cursed energy depleted. --- while (condition is false from the start) --- while block: executed 0 times --- do-while (condition is false from the start) --- do-while block: always executes at least once. do-while block: executed 1 time
WhileInfiniteBreak.java
public class WhileInfiniteBreak {
public static void main(String[] args) {
// --- Infinite loop with break ---
// Sorcerers take turns training; the session ends when Gojo Satoru appears
String[] members = {"Itadori Yuji", "Fushiguro Megumi", "Kugisaki Nobara", "Gojo Satoru", "Okkotsu Yuta"};
int index = 0;
System.out.println("=== Training Session ===");
while (true) { // Creates an infinite loop by using true as the condition
String current = members[index % members.length]; // Cycles through the array
System.out.println(current + " is training...");
if (current.equals("Gojo Satoru")) {
System.out.println("Gojo Satoru has arrived. Ending the training session.");
break; // Exits the infinite loop with break
}
index++;
}
// --- Using continue to skip the current iteration ---
// Nanami Kento only accepts missions during working hours (0:00–17:00)
System.out.println("\n=== Nanami Kento's Mission Hours (0:00–17:00) ===");
int hour = 0;
while (hour < 24) {
if (hour > 17) {
hour++;
continue; // Skips hours after 18:00 (no overtime)
}
System.out.println(hour + ":00 - Accepting missions");
hour++;
}
}
}
javac WhileInfiniteBreak.java java WhileInfiniteBreak === Training Session === Itadori Yuji is training... Fushiguro Megumi is training... Kugisaki Nobara is training... Gojo Satoru is training... Gojo Satoru has arrived. Ending the training session. === Nanami Kento's Mission Hours (0:00–17:00) === 0:00 - Accepting missions 1:00 - Accepting missions 2:00 - Accepting missions 3:00 - Accepting missions 4:00 - Accepting missions 5:00 - Accepting missions 6:00 - Accepting missions 7:00 - Accepting missions 8:00 - Accepting missions 9:00 - Accepting missions 10:00 - Accepting missions 11:00 - Accepting missions 12:00 - Accepting missions 13:00 - Accepting missions 14:00 - Accepting missions 15:00 - Accepting missions 16:00 - Accepting missions 17:00 - Accepting missions
DoWhileMenu.java
import java.util.Scanner;
public class DoWhileMenu {
public static void main(String[] args) {
// do-while is well suited for menu display and input loops
// The menu is shown at least once before reading input, and repeats until 0 is entered
Scanner scanner = new Scanner(System.in);
int choice;
System.out.println("=== Technique Selection Menu ===");
do {
// Because the block runs first, the menu is always displayed at least once
System.out.println("1: Unlimited Void");
System.out.println("2: Black Flash");
System.out.println("3: Reversal: Red");
System.out.println("0: Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("-> Unlimited Void activated.\n");
break;
case 2:
System.out.println("-> Black Flash activated.\n");
break;
case 3:
System.out.println("-> Reversal: Red activated.\n");
break;
case 0:
System.out.println("Exiting technique selection.");
break;
default:
System.out.println("Invalid choice. Please try again.\n");
}
} while (choice != 0); // Repeats the menu until 0 is entered
scanner.close();
}
}
javac DoWhileMenu.java java DoWhileMenu === Technique Selection Menu === 1: Unlimited Void 2: Black Flash 3: Reversal: Red 0: Exit Enter your choice: 2 -> Black Flash activated. 1: Unlimited Void 2: Black Flash 3: Reversal: Red 0: Exit Enter your choice: 0 Exiting technique selection.
Overview
The while loop is suited for processes where the number of iterations is not known in advance, or where it is acceptable to skip execution entirely if the condition is not met. The do-while loop is suited for flows where you need to perform an action first and then decide whether to continue — for example, displaying a menu, validating input, or managing game turns.
An infinite loop using while (true) is convenient when the exit condition is complex or there are multiple exit points. Always make sure the loop can exit via break or return. Forgetting to write an exit condition creates a true infinite loop, and the program will never stop.
When the number of iterations is known in advance, a for loop is often cleaner. For counter-based loops, see for loop. For reading standard input, see Scanner.
If you find any errors or copyright issues, please contact us.