Lesson 5 • Beginner
Java Loops
Imagine you need to print "Hello" 1,000 times, or add up every number in a list, or check every word in a document for spelling errors. You can't write 1,000 lines of code for that! Loops let you repeat a block of code as many times as you need — they're one of the most powerful concepts in all of programming.
What You'll Learn
- ✅
forloops — when you know exactly how many times to repeat - ✅
whileloops — when you don't know when to stop - ✅
do-whileloops — guaranteed to run at least once - ✅ Enhanced
for-eachloops — the easiest way to iterate over arrays - ✅
breakandcontinue— controlling loop flow - ✅ Nested loops — loops inside loops (multiplication tables, patterns)
- ✅ How to avoid the dreaded infinite loop
💡 Real-World Analogy
A loop is like a washing machine cycle. You set the conditions ("wash for 30 minutes" or "until the clothes are clean"), and the machine repeats the same actions (agitate, rinse) until the condition is met. A for loop is like a timed cycle ("run 10 times"). A while loop is like a sensor-based cycle ("keep going until clean").
1️⃣ The For Loop — "Repeat Exactly N Times"
The for loop is the most common loop in Java. Use it when you know how many times you want to repeat. It packs three things into one line: where to start, when to stop, and how to count.
// Anatomy of a for loop:
// for (start; keepGoing?; afterEach) { ... }
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// Output: i = 0, i = 1, i = 2, i = 3, i = 4
// Let's break it down:
// int i = 0 → Start: create counter at 0
// i < 5 → Condition: keep going while i is less than 5
// i++ → Update: add 1 to i after each loopStep-by-step execution:
int i = 0— create the counter (runs once)i < 5→ true → run the body → print "i = 0"i++→ i becomes 1i < 5→ true → run the body → print "i = 1"- ...continues until
ireaches 5 5 < 5→ false → loop ends
// Count by 2s (even numbers)
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " "); // 0 2 4 6 8 10
}
// Count backwards
for (int i = 10; i >= 0; i--) {
System.out.print(i + " "); // 10 9 8 7 6 5 4 3 2 1 0
}2️⃣ The While Loop — "Keep Going Until..."
The while loop checks its condition before each iteration. If the condition is false from the start, the body never runs at all. Use it when you don't know in advance how many iterations you need.
// Find the first power of 2 greater than 1000
int power = 1;
while (power <= 1000) {
power *= 2; // Double it each time
}
System.out.println(power); // 1024
// How many times did it loop? We didn't know in advance!
// It ran 10 times (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024)Common use case: Reading user input until they type "quit":
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.print("Enter command (or 'quit'): ");
input = scanner.nextLine();
System.out.println("You typed: " + input);
}⚠️ Critical: The condition variable (power, input) must change inside the loop. If it never changes, the condition never becomes false, and you get an infinite loop — your program freezes!
3️⃣ Do-While — "Do It At Least Once"
The do-while loop is like a while loop, but it checks the condition after running the body. This means the body always runs at least once, even if the condition is false. It's perfect for menu systems and input validation.
// Menu system — always show at least once
int choice;
do {
System.out.println("=== Game Menu ===");
System.out.println("1. Play");
System.out.println("2. Settings");
System.out.println("3. Quit");
System.out.print("Choose: ");
choice = scanner.nextInt();
} while (choice != 3);
// Input validation — keep asking until valid
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);🔑 while vs do-while: If the user might not need to see the prompt at all, use while. If you always want to show it at least once (menus, prompts), use do-while.
public class Main {
public static void main(String[] args) {
System.out.println("=== Loop Basics ===\n");
// 1. For loop — count 0 to 4
System.out.println("1. FOR LOOP (count 0-4):");
for (int i = 0; i < 5; i++) {
System.out.println(" i = " + i);
}
// 2. For loop — even numbers
System.out.print("\n2. FOR LOOP (even numbers 0-10):\n ");
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + (i < 10 ? ", " : ""));
}
System.out.println();
// 3. For loop — countdown
System.out.println("\n3. COUNTDOWN:");
for (int i = 5; i >= 1; i--) {
System.out.println(" " + i + "...");
}
System.out.println(" Liftoff!");
// 4. While loop — first power of 2 greater than 1000
System.out.println("\n4. WHILE LOOP (first power of 2 > 1000):");
int power = 1;
int count = 0;
while (power <= 1000) {
power *= 2;
count++;
}
System.out.println(" 2^" + count + " = " + power + " (took " + count + " iterations)");
// 5. Do-while — body always runs at least once
System.out.println("\n5. DO-WHILE (menu runs at least once):");
int[] choices = {1, 2, 3};
int idx = 0;
do {
int c = choices[idx];
String label = c == 1 ? "Play" : c == 2 ? "Settings" : "Quit";
System.out.println(" Choice " + c + " -> " + label);
idx++;
} while (idx < choices.length && choices[idx - 1] != 3);
System.out.println("\nThree loop types mastered!");
}
}=== Loop Basics ===
1. FOR LOOP (count 0-4):
i = 0
i = 1
i = 2
i = 3
i = 4
2. FOR LOOP (even numbers 0-10):
0, 2, 4, 6, 8, 10
3. COUNTDOWN:
5...
4...
3...
2...
1...
Liftoff!
4. WHILE LOOP (first power of 2 > 1000):
2^10 = 1024 (took 10 iterations)
5. DO-WHILE (menu runs at least once):
Choice 1 -> Play
Choice 2 -> Settings
Choice 3 -> Quit
Three loop types mastered!4️⃣ Enhanced For-Each — "For Every Item In..."
When you want to go through every item in an array or collection, the for-each loop is the cleanest option. No counter variable, no index, no chance of an off-by-one error.
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
// For-each: clean and simple
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}
// Reads as: "for each fruit in fruits"
// Compare with traditional for:
for (int i = 0; i < fruits.length; i++) {
System.out.println("I like " + fruits[i]);
}
// Same result, but more code and more room for bugs⚠️ When NOT to use for-each:
- When you need the index (e.g., "item 3 of 10")
- When you need to modify the array while looping
- When you need to loop backwards
In these cases, use a regular for loop instead.
5️⃣ Break & Continue — Loop Flow Control
Sometimes you need to exit a loop early or skip certain iterations. Java gives you two tools:
break — "Stop the loop NOW"
// Search for a value
int[] data = {10, 20, 30, 40, 50};
for (int i = 0; i < data.length; i++) {
if (data[i] == 30) {
System.out.println("Found at " + i);
break; // Stop searching
}
}
// Only checks 3 items, not all 5continue — "Skip this one"
// Sum only positive numbers
int[] nums = {5, -3, 8, -1, 12};
int sum = 0;
for (int n : nums) {
if (n < 0) continue; // Skip negatives
sum += n;
}
System.out.println("Sum: " + sum);
// Sum: 25 (5 + 8 + 12)💡 Use sparingly: Too many break and continue statements make code hard to follow. Often you can restructure your condition instead. But for search operations, break is perfectly natural.
6️⃣ Nested Loops — Loops Inside Loops
You can put a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. If the outer loop runs 3 times and the inner loop runs 4 times, the body runs 3 × 4 = 12 times total.
// Multiplication table (3×3)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + "\t");
}
System.out.println(); // New line after each row
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9Common uses: 2D grids (game boards, images), generating tables, comparing every pair of items, building patterns.
// Star pyramid pattern
for (int row = 1; row <= 5; row++) {
for (int star = 0; star < row; star++) {
System.out.print("* ");
}
System.out.println();
}
// *
// * *
// * * *
// * * * *
// * * * * *public class Main {
public static void main(String[] args) {
System.out.println("=== Nested Loops & Patterns ===\n");
// 1. Multiplication table (5x5)
System.out.println("1. MULTIPLICATION TABLE (5x5):");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print((i * j) + "\t");
}
System.out.println();
}
// 2. Star pyramid
System.out.println("\n2. STAR PYRAMID:");
for (int row = 1; row <= 5; row++) {
for (int star = 0; star < row; star++) {
System.out.print("* ");
}
System.out.println();
}
// 3. For-each with break (search)
System.out.println("\n3. SEARCH WITH BREAK:");
String[] names = {"Alice", "Bob", "Charlie", "Diana", "Eve"};
String target = "Charlie";
for (int i = 0; i < names.length; i++) {
System.out.println(" Checking: " + names[i]);
if (names[i].equals(target)) {
System.out.println(" Found " + target + " at index " + i + "!");
break;
}
}
// 4. continue — skip empty names
System.out.println("\n4. CONTINUE (skip empty names):");
String[] people = {"Alice", "", "Bob", null, "Charlie", ""};
int validCount = 0;
for (String name : people) {
if (name == null || name.isEmpty()) {
System.out.println(" Skipping empty entry");
continue;
}
validCount++;
System.out.println(" " + validCount + ". " + name);
}
}
}=== Nested Loops & Patterns ===
1. MULTIPLICATION TABLE (5x5):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
2. STAR PYRAMID:
*
* *
* * *
* * * *
* * * * *
3. SEARCH WITH BREAK:
Checking: Alice
Checking: Bob
Checking: Charlie
Found Charlie at index 2!
4. CONTINUE (skip empty names):
Skipping empty entry
1. Alice
Skipping empty entry
2. Bob
Skipping empty entry
3. Charlie
Skipping empty entry7️⃣ The Infinite Loop — And How to Avoid It
An infinite loop is a loop that never stops. Your program freezes, your CPU spins at 100%, and nothing else can happen. It's the most common loop bug:
// ❌ BUG: i never changes, so i < 10 is always true!
int i = 0;
while (i < 10) {
System.out.println("Stuck forever...");
// Forgot i++; !
}
// ❌ BUG: Wrong direction — i goes up but condition checks down
for (int i = 10; i >= 0; i++) { // Should be i--
System.out.println(i);
}
// ✅ Intentional infinite loop (used in servers and game loops)
while (true) {
String command = getInput();
if (command.equals("exit")) break; // Manual exit
processCommand(command);
}🛟 If your program is stuck in an infinite loop:
- In terminal: Press Ctrl + C to force-stop
- In IDE: Click the red "Stop" button
- To prevent: Always verify your loop variable changes in the right direction
8️⃣ Which Loop Should I Use?
Here's a simple decision guide:
| Question | Answer | Use |
|---|---|---|
| Do you know how many times? | Yes | for |
| Do you know how many times? | No | while |
| Must it run at least once? | Yes | do-while |
| Iterating an array/list? | Yes, all items | for-each |
public class Main {
public static void main(String[] args) {
System.out.println("=== Real-World Loop Problems ===\n");
// 1. Sum of 1 to 100 (Gauss's problem)
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("1. Sum of 1-100: " + sum + " (should be 5050)");
// 2. Factorial (5! = 5 * 4 * 3 * 2 * 1)
long fact = 1;
for (int i = 1; i <= 5; i++) fact *= i;
System.out.println("2. 5! = " + fact + " (should be 120)");
// 3. Find the minimum and maximum
int[] scores = {72, 95, 88, 63, 91, 77, 84};
int min = scores[0];
int max = scores[0];
for (int s : scores) {
if (s < min) min = s;
if (s > max) max = s;
}
System.out.println("3. Min: " + min + ", Max: " + max);
// 4. Count vowels in a string
String text = "Hello World";
int vowels = 0;
for (char ch : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) >= 0) vowels++;
}
System.out.println("4. Vowels in '" + text + "': " + vowels);
// 5. FizzBuzz (classic interview question!)
System.out.println("\n5. FIZZBUZZ (1-15):");
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) System.out.println(" " + i + " -> FizzBuzz");
else if (i % 3 == 0) System.out.println(" " + i + " -> Fizz");
else if (i % 5 == 0) System.out.println(" " + i + " -> Buzz");
else System.out.println(" " + i);
}
// 6. Reverse a string with a loop
String original = "Java";
StringBuilder reversed = new StringBuilder();
for (int i = original.length() - 1; i >= 0; i--) {
reversed.append(original.charAt(i));
}
System.out.println("\n6. Reverse '" + original + "' -> '" + reversed + "'");
}
}=== Real-World Loop Problems ===
1. Sum of 1-100: 5050 (should be 5050)
2. 5! = 120 (should be 120)
3. Min: 63, Max: 95
4. Vowels in 'Hello World': 3
5. FIZZBUZZ (1-15):
1
2
3 -> Fizz
4
5 -> Buzz
6 -> Fizz
7
8
9 -> Fizz
10 -> Buzz
11
12 -> Fizz
13
14
15 -> FizzBuzz
6. Reverse 'Java' -> 'avaJ'Common Mistakes
- ❌ Infinite loop — forgetting to update the counter:
while (i < 10) { ... } // ❌ Where is i++? - ❌ Off-by-one error: Using
<=when you meant<, or starting at 1 instead of 0. Arrays start at index 0! - ❌ Modifying a collection during for-each: You cannot add/remove items from an ArrayList while iterating with for-each. Use an Iterator or collect changes separately.
- ❌ Wrong loop variable in nested loops: Using
iin both outer and inner loop causes shadowing bugs. Use different names likeiandj.
Pro Tips
💡 Prefer for-each when possible — it's cleaner and prevents index errors. Only use a regular for loop when you need the index.
💡 Use meaningful variable names — for (String student : students) is much clearer than for (String s : arr).
💡 Extract loop bodies into methods — if the loop body is more than 5-10 lines, pull it into a separate method for readability.
💡 Consider Stream API later — once you learn Streams (Lesson 27), you'll often replace loops with .filter(), .map(), and .collect().
📋 Quick Reference
| Loop | Syntax | Best For |
|---|---|---|
| for | for (init; cond; update) | Known iteration count |
| while | while (condition) | Unknown count, check first |
| do-while | do { } while (cond); | Must run at least once |
| for-each | for (T item : collection) | Iterate all items in array/list |
| break | break; | Exit loop immediately |
| continue | continue; | Skip to next iteration |
🎉 Lesson Complete!
You've mastered all four types of Java loops, plus break and continue for flow control! You can now automate repetitive tasks, process arrays, build patterns, and even solve FizzBuzz — a classic coding interview question.
Next up: Methods — write reusable code blocks with parameters and return values to organize your programs into clean, testable pieces.
Sign up for free to track which lessons you've completed and get learning reminders.