Codectionary / Developer documentation / Java

while and do-while Loops

A while loop repeats its block as long as its condition remains true, checking the condition before each iteration - so the body might never execute at all. A do-while loop is similar, but checks the condition after the body runs, guaranteeing the loop body executes at least once. Both are ideal when the number of iterations isn't known ahead of time.

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

Specifications & further reading