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

작성자

카테고리:

← 피드로
DEV Community · Irza Hashim · 2026-07-05 개발(SW)

Irza Hashim

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.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다