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.
1️⃣ The while Loop
int i = 1
i <= 5 ?
print, then i++
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);
}
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished, i = 6
int i = 1is the start.i <= 5is the condition.i++is the update.- When
ibecomes 6 the condition is false, and the loop ends. That is whyiis 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 pass | number | digit = number % 10 | sum | number / 10 |
| 1 | 4728 | 8 | 8 | 472 |
| 2 | 472 | 2 | 10 | 47 |
| 3 | 47 | 7 | 17 | 4 |
| 4 | 4 | 4 | 21 | 0 (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);
}
}
Sum of digits of 4728 = 21
Reverse of 12345 = 54321
- Each pass uses
% 10to take the last digit and/ 10to 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
originalfirst, because the loop destroysnumber. - For the reverse,
reversed * 10 + digitshifts 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);
}
}
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
| while | do-while | |
| Test happens | before the body | after the body |
| Minimum runs | 0 times | 1 time |
| Ends with | } | } while (condition); (semicolon needed) |
| Best for | unknown number of repeats | menus, 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);
}
}
do-while body ran once, n = 10
- The condition
n < 5is false from the very start. Thewhilebody never runs, but thedo-whilebody 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.");
}
}
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.
choiceis declared before the loop, because a variable declared inside the braces would not be visible in thewhile (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)
}
}
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);
}
}
Bad2.java:8: error: cannot find symbol
System.out.println(x);
^
symbol: variable x
location: class Bad2
xwas declared inside the braces, so it disappears when the loop ends. Declare it before the loop if you need it afterwards.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Forgetting the update (i++) | Infinite loop | Make sure the condition can become false |
while (i <= 5); | Semicolon makes an empty loop body, likely infinite | Remove the ; |
Using < instead of <= | Off by one: the last value is skipped | Trace the first and last pass |
Missing ; after do-while | Compile error | } while (cond); |
| Changing the original number inside the loop | Value lost | Copy it first |
Using = in the condition | Compile error | Use == |
❓ 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.
whiletests first and may run zero times.do-whileruns at least once and ends with a semicolon.- Use
% 10and/ 10inside 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
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java