while loop vs do-while loop in Java

1. Introduction

In Java, loops are used to execute a set of statements repeatedly until a particular condition is satisfied. The while loop and the do-while loop are two forms of conditional loops that serve this purpose. A while loop evaluates its expression at the beginning of each loop cycle, so the code inside the loop may not execute at all if the condition is not met. A do-while loop evaluates its expression at the end of each loop cycle, which guarantees that the code inside the loop will execute at least once.

2. Key Points

1. A while loop checks the condition before the code within the loop is executed.

2. A do-while loop checks the condition after the code within the loop is executed.

3. As a result of the check timing, a while loop may not execute its code at all if the condition is initially false.

4. A do-while loop always executes its code block at least once.

3. Differences

while loop do-while loop
Condition checked before loop body execution. Condition checked after loop body execution.
May execute zero times. Guaranteed to execute at least once.
Syntax: while (condition) { statements; } Syntax: do { statements; } while (condition);

4. Example

public class LoopComparison {
    public static void main(String[] args) {
        int count = 0;

        // Step 1: Using a while loop
        System.out.println("while loop output:");
        while (count < 0) {
            System.out.println("This will not print");

        // Step 2: Using a do-while loop
        System.out.println("do-while loop output:");
        do {
            System.out.println("This will print at least once");
        } while (count < 0);


while loop output:
do-while loop output:
This will print at least once


1. The while loop with the condition count < 0 does not execute because the condition is false at the start.

2. The do-while loop, on the other hand, executes once before checking the condition count < 0, which is why the statement within the loop's body is printed.

5. When to use?

- Use a while loop when you want to execute code only if the condition is true at the start of the loop.

- Use a do-while loop when you want to ensure that the code within the loop executes at least once, regardless of the condition being true or false.