Skip to content
CampusEduX

Control Flow · Lesson 31 of 150

do-while Loop

A do-while loop is similar to a while loop, but it checks the condition after running the block once. This guarantees the code inside runs at least one time, no matter what.

1 min read

01What is a do-while Loop?

A do-while loop is similar to a while loop, but it checks the condition after running the block once. This guarantees the code inside runs at least one time, no matter what.

02Why is it used?

Some tasks must happen at least once before any check makes sense — like showing a menu to a user before asking if they want to continue. do-while guarantees this "at least once" behaviour.

03Real-Life Example

Think of a food tasting session: "Taste the dish once, then decide if you want to taste it again." You always taste it at least once before deciding whether to repeat — that's exactly how do-while behaves.

04Syntax

java
do { // code runs at least once } while (condition);

05Example Program

java
public class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 3); } }

Output:

Count: 1
Count: 2
Count: 3

06Key Points to Remember

  • The code block always runs at least once, even if the condition is false from the start.
  • Note the semicolon after while (condition); — a common beginner mistake is forgetting it.
  • Use do-while specifically when "run at least once" behaviour is required.