Skip to content

Java Loops πŸ”„

Mentor's Note: Computers are the best employees in the world because they never get tired of doing the same thing over and over. A loop is how you tell the computer to Repeat a task 100, 1000, or a million times! πŸ’‘


🌟 The Scenario: The School Bell & The Laundry 🧺

Imagine two different types of repetitive tasks.

  • The For Loop (The School Bell): A school bell rings exactly 8 times a day. πŸ”” You know the count before you even start.
  • The While Loop (The Laundry Basket): You keep washing clothes WHILE the basket is not empty. 🧺 You don't know if there are 5 shirts or 50!
  • The Do/While Loop (The First Plate): You wash at least ONE plate, then look at the pile to see if you should continue. 🍽️
  • The Result: Total automation of boring, repetitive tasks. βœ…

🎨 Visual Logic: The Loop Decision

Loop Type When to Use? Key Feature
for You know the count πŸ”” Compact (1 line setup)
while You wait for a condition 🧺 Check condition BEFORE running
do-while Run at least once 🍽️ Check condition AFTER running
for-each For every item in a list πŸ“¦ Simplest for Arrays
graph TD
    A[Start Loop πŸ”„] --> B{Condition True?}
    B -- Yes βœ… --> C[Execute Code βš™οΈ]
    C --> D[Update Counter/State ⬆️]
    D --> B
    B -- No ❌ --> E[Exit Loop πŸšͺ]

πŸ“– Concept Explanation

1. The for Loop πŸ”’

Used when you know exactly how many times to repeat. - Syntax: for (start; condition; update) - Logic: "Start at 1, go to 10, add 1 each time."

2. The while Loop 🧺

Used when you don't know the exact count, but you know the condition. - Warning: If the condition is always true, you get an Infinite Loop! ♾️

3. The do-while Loop 🍽️

Almost same as while, but it runs the code block once before checking the condition.

4. The for-each Loop πŸ“¦

The easiest way to go through an Array. - "For every name in names, print it."


πŸ’» Implementation: The Automation Lab

// πŸ›’ Scenario: School Bell & Laundry
// πŸš€ Action: Using for and while loops

public class Main {
    public static void main(String[] args) {
        // πŸ”” 1. For Loop: Ring the bell 8 times
        System.out.println("--- School Bell ---");
        for (int i = 1; i <= 8; i++) {
            System.out.println("Ring #" + i + " πŸ””");
        }

        // 🧺 2. While Loop: Wash till empty
        System.out.println("\n--- Laundry Day ---");
        int clothesInBasket = 5;
        while (clothesInBasket > 0) {
            System.out.println("Washing one shirt... 🧺");
            clothesInBasket--; // Important: Decrement or loop never ends!
        }

        // πŸ“¦ 3. For-Each Loop: List the students
        String[] students = {"Aryan", "Diya", "Kabir"};
        for (String s : students) {
            System.out.println("Student: " + s);
        }
    }
}

πŸ“Š Sample Dry Run (For Loop)

Turn Counter (i) Check (i <= 3) Output New Counter
1 1 true βœ… "Ring #1" 2 ⬆️
2 2 true βœ… "Ring #2" 3 ⬆️
3 3 true βœ… "Ring #3" 4 ⬆️
4 4 false ❌ EXIT LOOP πŸšͺ -

πŸ“ˆ Technical Analysis: The Infinite Loop ♾️

An infinite loop happens when your condition never becomes false. - Example: while (true) { ... } or forgetting the i++ in a for loop. - The Result: Your program hangs or crashes your computer! Always ensure your loop has an exit strategy. πŸ›‘οΈ


🎯 Practice Lab πŸ§ͺ

Task: The Multiplication Table

Task: Use a for loop to print the multiplication table of 5 (5 x 1 = 5, 5 x 2 = 10, etc.). Goal: Master the counter and loop multiplication. πŸ’‘


πŸ’‘ Interview Tip πŸ‘”

"Interviewers often ask: 'How many times will a do-while loop run if the condition is false from the start?' Answer: Exactly once. It checks the condition only after the first run."


πŸ’‘ Pro Tip: "Use for when you count, while when you wait. Choosing the right loop makes your code much easier to read!" - Vishnu Damwala


← Back: Switch | Next: Break & Continue β†’