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

    • for loops — when you know exactly how many times to repeat
    • while loops — when you don't know when to stop
    • do-while loops — guaranteed to run at least once
    • ✅ Enhanced for-each loops — the easiest way to iterate over arrays
    • break and continue — 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 loop

    Step-by-step execution:

    1. int i = 0 — create the counter (runs once)
    2. i < 5 → true → run the body → print "i = 0"
    3. i++ → i becomes 1
    4. i < 5 → true → run the body → print "i = 1"
    5. ...continues until i reaches 5
    6. 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.

    Try It: Loop Basics

    See for, while, and do-while loops in action

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Loop Basics — Java logic simulated in JavaScript
    console.log("=== Loop Basics ===\n");
    
    // 1️⃣ For Loop — count 0 to 4
    console.log("1. FOR LOOP (count 0-4):");
    for (let i = 0; i < 5; i++) {
      console.log("   i = " + i);
    }
    
    // 2️⃣ For Loop — even numbers
    console.log("\n2. FOR LOOP (even numbers 0-10):");
    let evens = [];
    for (let i = 0; i <= 10; i += 2) evens.push(i);
    console.log("   " + evens.join(", "));
    
    // 3️⃣ For Loop — countdown
    console.
    ...

    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 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();
    }
    // *
    // * *
    // * * *
    // * * * *
    // * * * * *

    Try It: Nested Loops & Patterns

    Build a multiplication table and star patterns

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Nested Loops — Java logic simulated in JavaScript
    console.log("=== Nested Loops & Patterns ===\n");
    
    // 1️⃣ Multiplication table
    console.log("1. MULTIPLICATION TABLE (5×5):");
    let header = "     ";
    for (let j = 1; j <= 5; j++) header += j + "\t";
    console.log(header);
    console.log("   " + "—".repeat(30));
    for (let i = 1; i <= 5; i++) {
      let row = " " + i + " | ";
      for (let j = 1; j <= 5; j++) {
        row += (i * j) + "\t";
      }
      console.log(ro
    ...

    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:

    • 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:

    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

    Try It: Real-World Loop Problems

    Sum numbers, calculate factorials, find min/max, and FizzBuzz

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Real-World Loops — Java logic simulated in JavaScript
    console.log("=== Real-World Loop Problems ===\n");
    
    // 1️⃣ Sum of 1 to 100 (Gauss's problem)
    let sum = 0;
    for (let i = 1; i <= 100; i++) sum += i;
    console.log("1. Sum of 1-100: " + sum + " (should be 5050)");
    
    // 2️⃣ Factorial (5! = 5 × 4 × 3 × 2 × 1)
    let fact = 1;
    for (let i = 1; i <= 5; i++) fact *= i;
    console.log("2. 5! = " + fact + " (should be 120)");
    
    // 3️⃣ Find the minimum and max
    ...

    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 i in both outer and inner loop causes shadowing bugs. Use different names like i and j.

    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 namesfor (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

    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.

    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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service