Syntax
while (condition) {\n // code\n}Examples
Basic while Loop
Repeating a block until a condition becomes false.
int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}
System.out.println("Done");do-while Loop
Guaranteeing the loop body runs at least once, since the condition is checked afterward.
int number;
java.util.Scanner scanner = new java.util.Scanner(System.in);
do {
System.out.println("Enter a positive number:");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);while Loop with break
Using while (true) with an internal break condition for more complex exit logic.
int attempts = 0;
while (true) {
attempts++;
if (attempts == 3) {
System.out.println("Success after " + attempts + " attempts");
break;
}
}Best practices
- Use a do-while loop specifically when the loop body must run at least once, such as displaying a menu before checking user input
- Always ensure the while condition will eventually become false, or include a break, to avoid an infinite loop
- Prefer a for loop when the number of iterations is known in advance - reserve while for genuinely condition-driven repetition
- Double-check that variables used in the loop condition are actually being updated somewhere inside the loop body
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification