Core Java Fundamentals ยท Loops

Do-While Loop

Learn about the do-while loop, a post-test (or exit-controlled) loop that guarantees the loop body is executed at least once.

DoWhileDemo.java

public class DoWhileDemo {
    public static void main(String[] args) {
        // Condition is initially false
        int count = 5;

        System.out.println("The loop will execute at least once.");

        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 5);

        System.out.println("Loop finished. Final count: " + count);
    }
}

Step by step

  1. We declare an integer variable count and initialize it to 5. Notice that the loop condition count < 5 is already false.
  2. A message is printed to the console before the loop begins.
  3. The program enters the do block. This happens without checking any condition. This is the key feature of a do-while loop.
  4. The code inside the loop body executes. The current value of count (5) is printed.
  5. The count variable is incremented. Its value changes from 5 to 6.
  6. Now, at the end of the loop block, the condition count < 5 is checked for the first time. Since 6 < 5 is false, the loop will not repeat.
  7. Execution continues to the statement after the loop. A final message is printed with the final value of count.