Java While Loop

Naveen AnamaneniUpdated · 4 min read

"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

Check, run, check again; leave when the condition is false
Savings.java▶ Try it
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);
    }
}
Output
Weeks needed: 7
Saved: Rs. 1050

How it works

  1. Line 5 checks saved < 1000. At the start, 0 < 1000 is true, so the body runs.
  2. Lines 6 and 7 add Rs. 150 and count one more week.
  3. Back to line 5. After 6 weeks, saved is 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:

UseWhen
forYou know the number of rounds: "5 laps", "every seat"
whileYou 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.

DigitSum.java▶ Try it
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);
    }
}
Output
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:

Orders.java▶ Try it
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);
    }
}
Output
Order total: Rs. 245

The 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

  1. Easy: Count how many digits a number has (for example, 40721 has 5) with a while loop.
  2. Harder: Reverse a number: 40721 becomes 12704. Hint: build the result with result = result * 10 + digit.

Quick check: while loop

4 questions
1When does a while loop check its condition?
2When is while a better choice than for?
3What happens if the body never changes the condition's variables?
4In DigitSum, what does number % 10 give for 4072?

Key Takeaways

Was this tutorial helpful?

Lesson 59 of 482