How many months to the new phone?
Riya wants a ₹10,000 phone. She can save ₹1,500 a month. She starts writing a for loop, then stops: for how many months? That's the very thing she's trying to find out.
Sir, I need a loop, but I don't know how many times it should run. That's the question!
Then don't count. Say what should keep it going: “while my savings are below ₹10,000, add another month”. Java checks the condition before each month and stops the moment it's false.
And I count the months inside the loop to get the answer.
Exactly. And there's a cousin, do-while, that runs the body first and checks afterwards. Let's see when each one is right.
What are while and do-while?
The while loop (while (condition) { body }) is an entry-controlled loop: the condition is evaluated before each iteration, so the body may execute zero times. The do-while loop (do { body } while (condition);) is an exit-controlled loop: the body executes first and the condition is evaluated afterwards, so the body executes at least once.
while: “check, then do”. Like checking the queue before joining: if nobody's there, you skip it entirely. do-while: “do, then check”. Like tasting the chai and then deciding whether it needs more sugar: you always taste at least once.
Words you'll meet in this lesson
while (true).n % 10 gives the last digit; n / 10 removes it.The three loops compared
| for | while | do-while | |
|---|---|---|---|
| Condition checked | Before each iteration | Before each iteration | After each iteration |
| Minimum runs | 0 | 0 | 1 |
| Best for | Known number of repeats | Repeat until something happens | Do once, then maybe repeat (menus, input checks) |
| Syntax ends with | } | } | } while (cond); ← semicolon |
Exam tip: the do-while ends with a semicolon after the condition; forgetting it is a compile error. For a while loop, the variables in the condition must be changed inside the body, or the loop never ends.
Common while-loop patterns
Until a goal is reached
while (savings < goal) { … }
Savings, loan payoff, population growth.
Digit by digit
while (n > 0) { d = n % 10; n /= 10; }
Reverse, count or add digits.
Sentinel input
Read numbers until the user enters 0, or lines until “exit”. The stop value isn't processed.
InputServer loop
while (running) { handle(next()); }
Keeps a service or game running until told to stop.
When do-while is the natural choice
| Situation | Why do-while |
|---|---|
| Showing a menu | The menu must appear at least once before the user can choose “Exit”. |
| Asking for input until it's valid | You must ask once before you can check the answer. |
| Processing the digits of a number, including 0 | 0 has one digit; a while loop with n > 0 would count zero digits. |
Writing a while loop that always ends
Set up variables before the loop
Unlike for, while has no init part. Everything the condition uses must already exist.int savings = 0; int months = 0;Write the condition as “keep going while…”
javac puts the check at the top: if it's false, jump past the loop (while (savings < 10_000) {if_icmpge). That's why a while loop can run zero times.Make progress inside the body
Each iteration must move the condition closer to false. Here savings grows, so eventually it reaches 10,000. If nothing changes, it's an infinite loop.savings += 1_500; months++; }Use the result after the loop
When the loop ends, the condition is guaranteed to be false:
At the end of the body, asavings >= 10_000.monthsholds the answer.gotojumps back to the check. When the check fails, execution continues after the loop.Switch to do-while when the body must run first
In bytecode, a do-while has its condition at the bottom:do { digitSum += n % 10; n /= 10; } while (n > 0);ifgtjumps back to the start if it's true. There's no check before the first iteration.
Check first, or do first? Both views
Left: the code and output. Right: the order of check and body, and the bytecode shape.
- The while loop checks
savings < 10_000before every iteration. - Each iteration adds ₹1,500 and counts a month. After 6 months: ₹9,000, still below the goal.
- After month 7, savings is ₹10,500, the condition is false, and the loop ends: 7 months.
- The do-while loop runs its body first: take the last digit, remove it.
- It checks
n > 0after each pass. 9 + 2 + 7 + 4 = 22. - The difference shows with 0: while runs zero times, do-while runs once. The number 0 has one digit.
- A while loop compiles to a check at the top, the body, and a
gotoback. - Each pass updates savings and months in the stack frame.
- On the 8th check, 10500 ≥ 10000, so
if_icmpgejumps to END. - A do-while has no check at the top: execution goes straight into the body.
- The check is at the bottom:
ifgt Ljumps back while n > 0. - Because the check comes last, the body always runs at least once.
“Until something happens” in real systems
Wherever software waits, retries, reads until the end, or runs until stopped, there's a while loop.
Watch it with an example: three tries to enter the OTP
A banking app gives you 3 attempts. A while loop keeps asking until the OTP is right or the attempts run out. Nobody knows in advance how many rounds it will take.
- Start: attempts = 0, ok = false. The condition is checked before the first round: true, so the loop body runs.
- Try 1: the user types 1111. Wrong. attempts becomes 1. Back to the condition: still true.
- Try 2: 4812 (two digits swapped). Wrong again. attempts = 2.
- Try 3: 4821. Correct: ok = true, attempts = 3.
- Exit: the condition is now false (both parts would stop it), so the loop ends and the app logs the user in.
- while vs do-while: a
whilecan run zero times. A menu that must appear at least once usesdo { … } while (…), which checks at the end.
1. Reading files and streams
Reading a log or CSV file line by line: while ((line = reader.readLine()) != null). Nobody knows in advance how many lines there are (Module 13).
2. Servers and background workers
A message consumer (for example a Kafka consumer) runs while (running) { poll(); process(); } for weeks, until it's asked to shut down.
3. Paging through an API
Many APIs return results page by page with a “next” link or cursor. Code keeps fetching while (nextCursor != null), collecting all pages.
4. Menus in terminals and kiosks
ATM-style and command-line menus use do-while: show the menu, handle the choice, repeat until the user picks Exit.
5. Financial projections
“How many years until this deposit doubles?” or “how many months to pay off this credit-card balance?” are while loops over months or years (see practice problem P10).
Examples are simplified to show where while loops fit. Real systems add timeouts and error handling.
Savings goal and digit sum
public class Main {
public static void main(String[] args) {
int savings = 0;
int months = 0;
while (savings < 10_000) { // check first
savings += 1_500;
months++;
}
System.out.println("Goal reached in " + months + " months: Rs " + savings);
int n = 4729, digitSum = 0;
do { // run first
digitSum += n % 10; // last digit
n /= 10; // remove it
} while (n > 0);
System.out.println("Digit sum: " + digitSum);
}
}while (savings < 10_000)Keep going while the goal isn't reached. We don't need to know how many months in advance.savings += 1_500;Progress: this is what eventually makes the condition false.n % 10The last digit of n (4729 % 10 = 9).n /= 10Removes the last digit using integer division (4729 / 10 = 472).} while (n > 0);The do-while's check, at the bottom, ending with a semicolon.
Watch the digits peel off
A do-while loop sums the digits of 472. Watch n shrink by one digit each pass, and where the condition is checked.
Worked examples: real problems, solved and traced in memory
Use while when you don't know in advance how many times to repeat: until a goal is reached, until a valid input arrives, until a number runs out of digits. In the traces, watch the condition being re-checked before (while) or after (do-while) each pass.
How many months to save for a laptop?
Problem statement
A student saves Rs 3,500 a month and also earns 1% interest per month on what's saved. How many months until she has Rs 15,000 for a laptop?
goal 15000, saves 3500/month, 1% per month
Months needed: 5 Balance then: Rs 17854
Approach
- Start with balance 0 and months 0.
- While the balance is below the goal: add interest, add the saving, count a month.
- The loop stops as soon as the goal is reached.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Three PIN attempts with do-while
Problem statement
An ATM allows up to 3 PIN attempts. The customer's attempts are in an array (simulating key presses). Use a do-while: the first attempt always happens, then repeat while the PIN is wrong and attempts remain.
correct PIN 4821; attempts 1234, 4812, 4821
Attempt 1: wrong Attempt 2: wrong Attempt 3: correct Card unlocked
Approach
do { … } while (…)runs the body at least once.- Each pass reads the next attempt and counts it.
- After the loop, decide: unlocked or card blocked.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Digit sum of an account number
Problem statement
Some systems use a digit sum as a quick check on account numbers. Add up the digits of 40021876 by repeatedly taking the last digit with % 10 and removing it with / 10.
40021876
8 digits, digit sum 28
Approach
- While the number is greater than 0:
- add
n % 10(last digit) to the sum, thenn /= 10. - Count the digits too.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 3.4 in one screen
while (cond) { … }— entry-controlled, may run 0 times.do { … } while (cond);— exit-controlled, runs at least once, ends with;.- Use while when the number of iterations isn't known: goals, files, sentinels, servers.
- The body must make progress towards ending the loop, or it's infinite.
- Digits:
n % 10= last digit,n / 10= remove it. - Bytecode: while checks at the top; do-while checks at the bottom with a backward jump.
Interview and viva questions
Difference between while and do-while?
while checks the condition before each iteration and can run zero times. do-while checks after each iteration and always runs at least once. Syntax-wise, do-while ends with a semicolon.
How do you exit an infinite while (true) loop?
With break (leave the loop), return (leave the method), an exception, or by ending the program. Long-running loops usually check a flag such as running that another part of the program can set to false.
Can a for loop always replace a while loop?
Yes: while (c) { … } is the same as for (; c; ) { … }. The choice is about readability: for says “count”, while says “until”.
What is a sentinel-controlled loop?
A loop that reads values until a special stop value (the sentinel) appears, such as 0 or “exit”. The sentinel itself isn't processed as data.
What is busy waiting, and why is it bad?
A loop that repeatedly checks a condition without pausing, like while (!ready) { }. It burns 100% of a CPU core doing nothing. Use blocking calls, sleeps with backoff, or proper concurrency tools (Module 12) instead.
Practice problems
These use while or do-while because the number of steps isn't known in advance. Try each one before opening the solution.
Count the digits
Count how many digits a positive number has.
n = 905213
905213 has 6 digits
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 905213;
int temp = n, count = 0;
do {
count++;
temp /= 10;
} while (temp > 0);
System.out.println(n + " has " + count + " digits");
}
}How it works: each / 10 removes one digit, so we count how many removals it takes to reach 0. We use a copy, temp, so the original n is still available to print. do-while makes 0 correctly count as 1 digit.
Reverse a number
Reverse the digits of a number.
n = 12345
Reversed: 54321
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 12345;
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
System.out.println("Reversed: " + reversed);
}
}How it works: take the last digit of n and “push” it onto the end of reversed by multiplying reversed by 10 and adding the digit: 0 → 5 → 54 → 543 → 5432 → 54321.
Product of digits
Multiply all the digits of a number together.
n = 2345
Product of digits: 120
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 2345;
int product = 1;
while (n > 0) {
product *= n % 10;
n /= 10;
}
System.out.println("Product of digits: " + product);
}
}How it works: same digit-peeling pattern, but a product accumulator starts at 1: 5 × 4 × 3 × 2 = 120.
Palindrome number
A palindrome reads the same forwards and backwards. Check whether a number is a palindrome.
n = 12321
12321 is a palindrome
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 12321;
int temp = n, reversed = 0;
while (temp > 0) {
reversed = reversed * 10 + temp % 10;
temp /= 10;
}
if (reversed == n) {
System.out.println(n + " is a palindrome");
} else {
System.out.println(n + " is not a palindrome");
}
}
}How it works: reverse a copy of the number (problem P2), then compare it with the original. Keeping the original untouched is the key detail.
Armstrong number
A 3-digit number is an Armstrong number if the sum of the cubes of its digits equals the number itself (e.g. 153 = 1³ + 5³ + 3³). Check a number.
n = 153
153 is an Armstrong number
Show solution and explanation
public class Main {
public static void main(String[] args) {
int n = 153;
int temp = n, sum = 0;
while (temp > 0) {
int d = temp % 10;
sum += d * d * d;
temp /= 10;
}
System.out.println(n + (sum == n ? " is" : " is not") + " an Armstrong number");
}
}How it works: peel each digit, cube it with d * d * d (faster and exact compared with Math.pow, which returns a double), and add it up: 27 + 125 + 1 = 153.
GCD and LCM (Euclid's algorithm)
Find the greatest common divisor (GCD) and least common multiple (LCM) of two numbers.
a = 48, b = 180
GCD = 12, LCM = 720
Show solution and explanation
public class Main {
public static void main(String[] args) {
int a = 48, b = 180;
int x = a, y = b;
while (y != 0) {
int remainder = x % y;
x = y;
y = remainder;
}
int gcd = x;
int lcm = a / gcd * b;
System.out.println("GCD = " + gcd + ", LCM = " + lcm);
}
}How it works: Euclid's rule: gcd(x, y) = gcd(y, x % y), until y is 0. Steps: (48, 180) → (180, 48) → (48, 36) → (36, 12) → (12, 0). Then LCM = a × b ÷ GCD; dividing first (a / gcd * b) keeps numbers small and avoids overflow.
Collatz steps
Start with n. If it's even, halve it; if odd, make it 3n + 1. Count the steps until n becomes 1.
n = 27
27 reaches 1 in 111 steps
Show solution and explanation
public class Main {
public static void main(String[] args) {
int start = 27;
long n = start;
int steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println(start + " reaches 1 in " + steps + " steps");
}
}How it works: a perfect while-loop problem: nobody knows the number of steps in advance. Values can climb high before falling (27 goes past 9,000), so we use long to be safe from overflow.
Guess the number in the fewest tries
A secret number is between 1 and 100. Each guess is answered “higher” or “lower”. Always guess the middle of the remaining range, and print each guess and the number of tries.
secret = 37
Guesses: 50 25 37 Found in 3 tries
Show solution and explanation
public class Main {
public static void main(String[] args) {
int secret = 37;
int low = 1, high = 100, tries = 0;
System.out.print("Guesses:");
while (low <= high) {
int guess = (low + high) / 2;
tries++;
System.out.print(" " + guess);
if (guess == secret) {
break;
} else if (guess < secret) {
low = guess + 1; // answer was "higher"
} else {
high = guess - 1; // answer was "lower"
}
}
System.out.println();
System.out.println("Found in " + tries + " tries");
}
}How it works: this is binary search. Each guess halves the remaining range, so any number from 1 to 100 is found in at most 7 tries (27 = 128). The loop runs while the range is non-empty and stops early with break when found.
ATM PIN with 3 attempts
An ATM allows 3 PIN attempts. The entered PINs for one session are given in order. Print “Access granted on attempt k”, or “Card blocked” if all 3 attempts fail.
correct PIN = 4321 entered = 1111, 2580, 4321
Attempt 1: wrong PIN Attempt 2: wrong PIN Access granted on attempt 3
Show solution and explanation
public class Main {
public static void main(String[] args) {
final int CORRECT_PIN = 4321;
final int MAX_ATTEMPTS = 3;
int[] entered = {1111, 2580, 4321}; // what the customer typed
int attempt = 0;
boolean granted = false;
do {
int pin = entered[attempt];
attempt++;
if (pin == CORRECT_PIN) {
granted = true;
} else {
System.out.println("Attempt " + attempt + ": wrong PIN");
}
} while (!granted && attempt < MAX_ATTEMPTS);
if (granted) {
System.out.println("Access granted on attempt " + attempt);
} else {
System.out.println("Card blocked");
}
}
}How it works:
- do-while fits because the customer must be asked at least once.
- The loop has two reasons to stop, combined with
&&: success, or running out of attempts. - After the loop, the
grantedflag tells us why it stopped. Change the last PIN to 9999 to see “Card blocked”. - Real ATMs never store or compare plain PINs like this; the card and bank verify them securely. The loop logic is the same, though.
When will the fixed deposit double?
A customer invests ₹50,000 in a fixed deposit at 7% per year, compounded yearly. How many years until it reaches at least ₹1,00,000, and what will it be worth then? (Compare with the “Rule of 72” estimate: 72 ÷ 7 ≈ 10.3 years.)
amount = 50000, rate = 7%, target = 100000
Doubles after 11 years Value then: Rs 105242.60
Show solution and explanation
public class Main {
public static void main(String[] args) {
double amount = 50_000;
double ratePercent = 7;
double target = 100_000;
int years = 0;
while (amount < target) {
amount += amount * ratePercent / 100; // one year of interest
years++;
}
System.out.println("Doubles after " + years + " years");
System.out.printf("Value then: Rs %.2f%n", amount);
}
}How it works:
- Each pass adds one year's interest on the current amount: that's compounding.
- After 10 years the amount is about ₹98,358, just short; year 11 takes it past the target. The Rule of 72 (≈ 10.3 years) is a good mental estimate.
- The loop condition matches the business question exactly: “keep going while it's below the target”.
- Real deposit calculations follow the bank's rules (quarterly compounding, TDS) and use BigDecimal for exact money.
Real-world scenario questions (asked in company interviews)
Loops that run “until something happens” are where systems hang and burn CPU. Decide your answer first, then open the model answer.
A waiting loop that uses 100% CPU
A job waits for a file to arrive from a partner with while (!Files.exists(path)) { }. The ops team reports one CPU core stuck at 100% for hours whenever the partner is late. What's wrong and what would you do?
The interviewer is checking: do you recognise busy waiting and know better alternatives?
Show a strong answer
This is busy waiting: the empty loop checks the file system millions of times a second without pausing.
- Sleep between checks (e.g.
Thread.sleep(30_000)), ideally with a growing delay, and a maximum wait time after which the job alerts someone. - Better: react to events instead of polling: Java's
WatchServicefor file system changes, or have the partner send a message or API call when the file is ready. - Add monitoring so late files are visible, not just a hot CPU.
Avoid: an empty while body that waits for something external.
Downloading transactions never finishes
A job fetches bank transactions page by page with while (cursor != null) { page = api.fetch(cursor); … cursor = page.next(); }. One night the partner API had a bug and kept returning the same cursor. The job ran for 9 hours and filled the disk with duplicates. How would you make the loop safe?
The interviewer is checking: do you defend loops that depend on external systems?
Show a strong answer
- Detect lack of progress: if the new cursor equals the previous one (or a page returns zero items), stop and raise an alert.
- Add a safety limit: a maximum number of pages or a time budget, beyond which the job stops and alerts.
- Make writes idempotent (e.g. upsert by transaction ID), so repeated pages don't create duplicates.
- Log progress per page so you can resume from the last good cursor.
Avoid saying: “The partner's API should be correct.” Our code must protect itself.
One bad order blocks all the others
An order processor runs while (!queue.isEmpty()) { Order o = queue.poll(); try { process(o); } catch (Exception e) { queue.add(o); } }. One order has corrupted data and always fails. Soon the worker spends all its time retrying it, and other orders are delayed. What's the fix?
The interviewer is checking: do you know about poison messages, retry limits and dead-letter queues?
Show a strong answer
The corrupted order is a poison message: it can never succeed, but the loop retries it forever.
- Track a retry count per message; after a few attempts (with a delay between them), stop retrying.
- Move it to a dead-letter queue where people can inspect and fix it, and raise an alert.
- Separate failures that can succeed later (a timeout) from ones that can't (invalid data), and only retry the first kind.
Avoid: silently dropping the order. Someone paid for it.
The menu that shows up twice
A passbook-printing kiosk shows its menu with this code: showMenu(); int choice = read(); while (choice != 4) { handle(choice); showMenu(); choice = read(); }. A reviewer says it works but suggests a do-while. Why might do-while be clearer here?
The interviewer is checking: do you know when “at least once” is the natural shape of a loop?
Show a strong answer
The menu must be shown and read at least once. With while, the “show and read” code is written twice (before the loop and at the end of it), and the two copies can drift apart when someone edits one.
- With do-while it's written once:
do { showMenu(); choice = read(); if (choice != 4) handle(choice); } while (choice != 4); - Add input validation and a timeout, so an abandoned kiosk returns to the home screen.
Avoid saying: “Both work, so it doesn't matter.” Duplicated code is a maintenance risk.