Loops

Reviewed & published by Brayan K

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.

Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn

💡 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 loop
// 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!");
    }
}

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:

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 5

continue — "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   9

Common 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);
        }
    }
}

7️⃣ 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:

8️⃣ Which Loop Should I Use?

Here's a simple decision guide:

QuestionAnswerUse
Do you know how many times?Yesfor
Do you know how many times?Nowhile
Must it run at least once?Yesdo-while
Iterating an array/list?Yes, all itemsfor-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 + "'");
    }
}
public class Main {
    public static void main(String[] args) {
        // 🎯 YOUR TURN — replace each ___ using the hint beside it.

        double[] prices  = {4.50, 0.00, 12.99, 3.20, 0.00, 25.00, 7.75};
        double   cardCap = 40.00;

        double total   = 0;
        int    scanned = 0;

        // 1) Walk every price by index. Stop BEFORE the length, never at it.
        for (int i = 0; i ___ prices.length; i++) {   // 👉 replace ___ with <

            // 2) A voided line is 0.00 — skip to the next turn of the loop.
            if (prices[i] == 0.00) {
                ___;                                   // 👉 replace ___ with continue
            }

            // 3) Adding this one would pass the card cap — leave the loop entirely.
            if (total + prices[i] > cardCap) {
                System.out.printf("Line %d would pass the cap - stopping%n", i);
                ___;                                   // 👉 replace ___ with break
            }

            total += prices[i];
            scanned++;
        }

        System.out.println("Items rung up: " + scanned);
        System.out.printf("Total: %.2f%n", total);

        // 4) Count down to zero. Forget this line and the loop never ends.
        int countdown = 3;
        while (countdown > 0) {
            System.out.println("Printing receipt in " + countdown);
            ___;                                       // 👉 replace ___ with countdown--
        }

        // 5) do-while runs its body once BEFORE it ever tests the condition,
        //    which is why this prints even though countdown is already 0.
        ___ {                                          // 👉 replace ___ with do
            System.out.println("Receipt printed once, whatever the count.");
        } while (countdown > 0);
    }
}

Common Mistakes

while (i < 10) { ... }  // ❌ Where is i++?

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 the Streams API, you'll often replace loops with .filter(), .map(), and .collect().

📋 Quick Reference

LoopSyntaxBest For
forfor (init; cond; update)Known iteration count
whilewhile (condition)Unknown count, check first
do-whiledo { } while (cond);Must run at least once
for-eachfor (T item : collection)Iterate all items in array/list
breakbreak;Exit loop immediately
continuecontinue;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.

Practice quiz

Which loop is best when you know exactly how many times to repeat?

  • while
  • do-while
  • for
  • if

Answer: for. A for loop packs start, condition, and update into one line — ideal for a known count.

How many times does 'for (int i = 0; i < 5; i++)' run its body?

  • 4
  • 5
  • 6
  • Infinite

Answer: 5. i goes 0,1,2,3,4 — that is 5 iterations; it stops when i reaches 5.

What makes a do-while loop different from a while loop?

  • It never stops
  • Its body always runs at least once
  • It cannot use a condition
  • It only works with arrays

Answer: Its body always runs at least once. do-while checks the condition AFTER the body, so the body always runs at least once.

What does the break statement do inside a loop?

  • Skips the current iteration
  • Exits the loop immediately
  • Restarts the loop
  • Pauses for a second

Answer: Exits the loop immediately. break exits the loop immediately; continue is what skips to the next iteration.

What does continue do inside a loop?

  • Exits the loop
  • Skips the rest of this iteration and moves to the next
  • Ends the program
  • Doubles the counter

Answer: Skips the rest of this iteration and moves to the next. continue skips the remaining body for this iteration and proceeds to the next one.

If an outer loop runs 3 times and an inner loop runs 4 times, how many times does the inner body run total?

  • 7
  • 12
  • 3
  • 4

Answer: 12. Nested loops multiply: 3 × 4 = 12 total executions of the inner body.

What is the most common cause of an infinite while loop?

  • Using a for-each
  • The condition variable never changes
  • Using break
  • Declaring too many variables

Answer: The condition variable never changes. If the variable in the condition never changes, the condition stays true forever — an infinite loop.

Which loop is cleanest for reading every element of an array without an index?

  • do-while
  • while
  • for-each (enhanced for)
  • switch

Answer: for-each (enhanced for). The for-each loop iterates every element with no counter or index, avoiding off-by-one bugs.

In the lesson, 'while (power <= 1000) power *= 2;' starting at power = 1 ends with power equal to what?

  • 512
  • 1000
  • 1024
  • 2048

Answer: 1024. Doubling 1 ten times reaches 1024, the first power of 2 greater than 1000.

Why is 'for (int i = 10; i >= 0; i++)' a bug?

  • i++ moves i away from the stop condition, looping forever
  • You cannot start at 10
  • i >= 0 is invalid
  • It runs exactly once

Answer: i++ moves i away from the stop condition, looping forever. Counting up (i++) while the condition checks i >= 0 never becomes false — it should be i--.

Continue this course