Java While Loop
"Keep pouring water until the bucket is full." You don't know how many mugs it will take; you just keep going while the bucket isn't full. That's a while loop: it repeats a block as long as a condition is true, without needing to know the number of rounds in advance.
How while Works
public class Savings {
public static void main(String[] args) {
int saved = 0;
int weeks = 0;
while (saved < 1000) {
saved += 150;
weeks++;
}
System.out.println("Weeks needed: " + weeks);
System.out.println("Saved: Rs. " + saved);
}
}Weeks needed: 7
Saved: Rs. 1050How it works
- Line 5 checks
saved < 1000. At the start,0 < 1000is true, so the body runs. - Lines 6 and 7 add Rs. 150 and count one more week.
- Back to line 5. After 6 weeks,
savedis 900 (still less than 1000); after 7 weeks it's 1050, the condition is false, and the loop ends.
Try it yourself: change the weekly saving to Rs. 250. How many weeks now?
while vs for
Both loops can do the same job; choose the one that reads better:
| Use | When |
|---|---|
for | You know the number of rounds: "5 laps", "every seat" |
while | You repeat until something happens: "until the target is reached", "until the user types quit" |
A for loop is really a while loop with the counter written in its header.
Processing Digits
A classic while job: take a number apart digit by digit, without knowing in advance how many digits it has.
public class DigitSum {
public static void main(String[] args) {
int number = 40721;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit;
number = number / 10;
}
System.out.println("Sum of digits: " + sum);
}
}Sum of digits: 14% 10 gives the last digit and / 10 removes it: 40721 → 4072 → 407 → 40 → 4 → 0. The digits 1, 2, 7, 0 and 4 add up to 14.
Reading Input Until a Signal
while is the natural loop for input whose length you don't know:
import java.util.Scanner;
public class Orders {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
int price = sc.nextInt();
while (price != 0) {
total += price;
price = sc.nextInt();
}
System.out.println("Order total: Rs. " + total);
}
}Order total: Rs. 245The user types prices and finishes with 0. The first price is read before the loop, so the condition has something to check; each round reads the next price at the end.
Common Mistakes
Forgetting to update the variable. The loop never ends. The lesson "Infinite Loops" covers this.
Not initializing before the loop. The condition is checked first, so its variables need values before the loop starts.
Using while for a fixed count. for (int i = 0; i < 10; i++) is clearer than managing i yourself.
Practice
- Easy: Count how many digits a number has (for example, 40721 has 5) with a
whileloop. - Harder: Reverse a number: 40721 becomes 12704. Hint: build the result with
result = result * 10 + digit.
Key Takeaways
Was this tutorial helpful?