Java for Beginners, Lesson 18: while and do-while Loops in Java

Java for Beginners · Module 4: Control Flow


🎯 Doing Things Again and Again

Printing the numbers 1 to 5 needs five lines. Printing 1 to 1000 should not need a thousand. A loop repeats a block of code as long as a condition stays true. Java has three loops: while, do-while and for. This lesson covers the first two.

📌 A while loop tests its condition first, then runs the body. A do-while loop runs the body first, then tests, so it always runs at least once.

1️⃣ The while Loop

1. Initialise
int i = 1
➜
2. Test
i <= 5 ?
true ➜
3. Body
print, then i++
back to 2
false ➜ exit the loop

Figure 1: The cycle of a while loop: test first, then run the body.

Every loop that counts needs three parts: a starting value, a condition and an update that moves towards ending.

public class WhileDemo {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
        System.out.println("Loop finished, i = " + i);
    }
}
🖥️ Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished, i = 6
  • int i = 1 is the start. i <= 5 is the condition. i++ is the update.
  • When i becomes 6 the condition is false, and the loop ends. That is why i is 6 afterwards.
  • If you forget i++, the condition never becomes false and the loop runs forever. This is an infinite loop. Stop a running program with Ctrl + C.

2️⃣ while for Repeating Until Something Happens

A while loop is the natural choice when you do not know in advance how many times to repeat. Splitting a number into digits is a classic example: the loop continues until nothing is left.

Loop passnumberdigit = number % 10sumnumber / 10
1472888472
247221047
3477174
444210 (stop)

Figure 3: Tracing the digit-sum loop for 4728.

public class DigitSum {
    public static void main(String[] args) {
        int number = 4728;
        int original = number;
        int sum = 0;
        while (number > 0) {
            int digit = number % 10;
            sum += digit;
            number /= 10;
        }
        System.out.println("Sum of digits of " + original + " = " + sum);

        int n = 12345, reversed = 0;
        while (n != 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        System.out.println("Reverse of 12345 = " + reversed);
    }
}
🖥️ Output:
Sum of digits of 4728 = 21
Reverse of 12345 = 54321
  • Each pass uses % 10 to take the last digit and / 10 to drop it (Lesson 12).
  • The loop does not know there are four digits. It simply stops when the number reaches 0.
  • The number is saved in original first, because the loop destroys number.
  • For the reverse, reversed * 10 + digit shifts the earlier digits left and attaches the new one.

A number sequence with an unpredictable length (the Collatz sequence):

public class Collatz {
    public static void main(String[] args) {
        int n = 6, steps = 0;
        System.out.print(n);
        while (n != 1) {
            n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
            System.out.print(" -> " + n);
            steps++;
        }
        System.out.println();
        System.out.println("Steps: " + steps);
    }
}
🖥️ Output:
6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Steps: 8
  • If n is even, halve it. If odd, triple it and add 1. It uses the ternary operator from Lesson 15.
  • Nobody can say before the loop starts how many steps it will need, which makes while the right tool.

3️⃣ The do-while Loop

whiledo-while
Test happensbefore the bodyafter the body
Minimum runs0 times1 time
Ends with}} while (condition); (semicolon needed)
Best forunknown number of repeatsmenus, input that must be read at least once

Figure 2: while versus do-while.

A do-while loop checks the condition after each pass, so its body always runs at least once.

public class DoWhileDemo {
    public static void main(String[] args) {
        int n = 10;
        while (n < 5) {
            System.out.println("while body ran");
        }
        do {
            System.out.println("do-while body ran once, n = " + n);
        } while (n < 5);
    }
}
🖥️ Output:
do-while body ran once, n = 10
  • The condition n < 5 is false from the very start. The while body never runs, but the do-while body runs once before the test.
  • Do not forget the semicolon after while (condition) in a do-while.

Program 5: A menu that repeats until the user quits

import java.util.Scanner;

public class Menu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;
        do {
            System.out.println("1. Say hello   2. Say bye   0. Exit");
            System.out.print("Choice: ");
            choice = sc.nextInt();
            if (choice == 1) System.out.println("Hello!");
            else if (choice == 2) System.out.println("Bye!");
        } while (choice != 0);
        System.out.println("Program ended.");
    }
}
🖥️ Output (bold = what the user types):
1. Say hello 2. Say bye 0. Exit
Choice: 1
Hello!
1. Say hello 2. Say bye 0. Exit
Choice: 2
Bye!
1. Say hello 2. Say bye 0. Exit
Choice: 7
1. Say hello 2. Say bye 0. Exit
Choice: 0
Program ended.
  • A menu must be shown at least once, so do-while fits perfectly.
  • choice is declared before the loop, because a variable declared inside the braces would not be visible in the while (choice != 0) test (Lesson 11).
  • Typing 7 matches nothing, so the menu simply shows again.

4️⃣ Errors Beginners Meet

Missing semicolon after a do-while

public class Bad1 {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 3)
    }
}
🖥️ Compiler message:
Bad1.java:7: error: ‘;’ expected
} while (i <= 3)
^
1 error

Using a loop variable outside the loop body

public class Bad2 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 3) {
            int x = i * 2;
            i++;
        }
        System.out.println(x);
    }
}
🖥️ Compiler message:
Bad2.java:8: error: cannot find symbol
System.out.println(x);
^
symbol: variable x
location: class Bad2
  • x was declared inside the braces, so it disappears when the loop ends. Declare it before the loop if you need it afterwards.

⚠️ Common Mistakes

MistakeProblemFix
Forgetting the update (i++)Infinite loopMake sure the condition can become false
while (i <= 5);Semicolon makes an empty loop body, likely infiniteRemove the ;
Using < instead of <=Off by one: the last value is skippedTrace the first and last pass
Missing ; after do-whileCompile error} while (cond);
Changing the original number inside the loopValue lostCopy it first
Using = in the conditionCompile errorUse ==

❓ Frequently Asked Questions

Q1. Which loop should I choose?
Use while when the number of repeats is unknown. Use do-while when the body must run at least once. Use for (Lesson 19) when you know the count.

Q2. Can a loop be infinite on purpose?
Yes: while (true) { ... } with a break inside to leave (Lesson 20). Servers and games use this idea.

Q3. How do I stop an infinite loop?
Press Ctrl + C in the terminal, or use the stop button in your IDE.

Q4. Can I put one loop inside another?
Yes. That is called a nested loop, and Lesson 19 uses it to print patterns.

✅ Key Takeaways

  • A loop needs a start, a condition and an update.
  • while tests first and may run zero times. do-while runs at least once and ends with a semicolon.
  • Use % 10 and / 10 inside a while loop to process digits.
  • If the condition never becomes false, the loop is infinite.
  • Variables declared inside the braces are not visible after the loop.
🎓 Practice questions: (1) Print the even numbers from 2 to 20 using a while loop. (2) Count the digits of a number. (3) Check whether a number is a palindrome (it equals its reverse). (4) Why does a menu program suit do-while better than while? (5) Trace the loop int i = 10; while (i > 0) { i -= 3; } and say the final value of i.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision