Java Do-While Loop — Java Technical Interview Questions & Answers
Java Do-While Loop
Java Do-While Loop
- do-while runs the body first, then checks. So it always runs at least once. Shape: do { body } while (condition); — the semicolon at the end is required.
- Order: body → check → maybe body again. Use it when you must do something once before you can decide: show a menu, ask for input once.
- while can skip the body completely. do-while cannot. Freshers forget the semicolon after while (condition) and get a compile error.
- Let's take this on the board with one tiny Main class — no extra files. Java Do-While Loop — output: 1 then 2 then 3. do-while runs the body first, then checks. Even if i started at 9, one print would still happen. Start from main, go line by line, and stop at each print. That output is the proof for Do-While Loop.
body first
│
▼
check ── true → body again
│ false
▼
stopTechnical Interview Tip: One line: do-while guarantees one execution. Show a menu loop.
Code Examples for Java Do-While Loop
Example
// Java Do-While — prints 1, 2, 3
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 3);
}
}Java Do-While Loop — output: 1 then 2 then 3. do-while runs the body first, then checks. Even if i started at 9, one print would still happen.
How to Explain Java Do-While Loop to an Interviewer
How many times does do-while run at minimum?
At least once
What is the order?
Body first Then check
What do people forget?
Semicolon after while (condition)