Java While vs. Do-While Loops: The Critical Difference

java dev.to

In Java, both while and do-while loops repeat a block of code as long as a condition is true. However, there is one critical difference between them: when the condition is checked.

Let's look at how they work using two simple code examples.

1. The Java While Loop

A while loop checks the condition before executing the code block. If the condition is false at the very beginning, the code inside the loop will never run.

int ticketCount = 0;

while (ticketCount > 0) {
    System.out.println("Watching the movie...");
    ticketCount--;
}
Enter fullscreen mode Exit fullscreen mode

Why it works:

Because ticketCount is 0, the condition ticketCount > 0 is instantly false. The computer skips the loop completely. Nothing prints on the screen.

2. The Java Do-While Loop

A do-while loop executes the code block first, and then checks the condition at the end. This means the loop will always run at least once, even if the condition is completely false.

int ticketCount = 0;

do {
    System.out.println("Trying the ride once...");
    ticketCount--;
} while (ticketCount > 0);
Enter fullscreen mode Exit fullscreen mode

Why it works:

The computer enters the do block first and prints the message. Then it checks the condition ticketCount > 0. Since it is false, the loop stops.

The Output Summary

If you run both codes, your terminal output will look like this:

[While Loop Output]: (Nothing prints)

[Do-While Loop Output]:
Trying the ride once...
Enter fullscreen mode Exit fullscreen mode

Key Conclusion for Beginners

  • Use a while loop when you want to check the condition first.
  • Use a do-while loop when you need the code to run at least one time, no matter what.

Source: dev.to

arrow_back Back to Tutorials