☕ Java Loops — Complete Deep Revision Guide

📖 Loops Kya Hain?

Bina loop ke:              Loop ke saath:
print("Hello");            for(int i=0; i<5; i++) {
print("Hello");                print("Hello");
print("Hello");            }
print("Hello");            // sirf 4 lines mein same kaam!
print("Hello");

Loop = Ek kaam baar baar karo jab tak condition true hai

for      → Jab pata ho kitni baar chalana hai
while    → Jab condition pe depend karna ho
do-while → Kam se kam EK baar zaroor chalana ho
for-each → Array/Collection ke har element pe kaam

🔵 Topic 1: for Loop

Deep Explanation — Memory Mein Kaise Kaam Karta Hai:

for (initialization ; condition ; update) {
         ↑                ↑           ↑
    Step 1: ek baar   Step 2: har   Step 4: body ke
    shuru mein        iteration se  baad update
                      pehle check
         ↓                ↓           ↑
                      TRUE → body    ← Step 3: body
                      FALSE → exit       execute

Execution Order:

1. initialization  → sirf ek baar
2. condition check → true? → 3. body → 4. update → 2. again
                  → false? → loop khatam

Teen Parts Optional Hain:

for(;;)             // infinite loop - teeno skip
for(;i<5;)          // init aur update bahar
for(int i=0;;i++)  // condition nahi - infinite
📁 ForLoop1.java
public class ForLoop1 {
    public static void main(String[] args) {

        // Basic for loop - step by step trace
        System.out.println("Basic for loop:");
        for (int i = 1; i <= 5; i++) {
            System.out.println("i = " + i);
        }
        // Step trace:
        // i=1: 1<=5 true  → print 1 → i becomes 2
        // i=2: 2<=5 true  → print 2 → i becomes 3
        // i=3: 3<=5 true  → print 3 → i becomes 4
        // i=4: 4<=5 true  → print 4 → i becomes 5
        // i=5: 5<=5 true  → print 5 → i becomes 6
        // i=6: 6<=5 false → STOP

        System.out.println("\nBackward loop:");
        for (int i = 5; i >= 1; i--) {
            System.out.println("i = " + i);
        }

        System.out.println("\nStep of 2:");
        for (int i = 0; i <= 10; i += 2) {
            System.out.print(i + " ");
        }
    }
}
▶ OUTPUT
Basic for loop: i = 1 i = 2 i = 3 i = 4 i = 5 Backward loop: i = 5 i = 4 i = 3 i = 2 i = 1 Step of 2: 0 2 4 6 8 10
💡 i=1 se shuru, i<=5 condition, i++ har baar. Jab i=6 hota hai condition false hoti hai aur loop khatam. Backward mein i-- use karo.
📁 ForLoop2.java
public class ForLoop2 {
    public static void main(String[] args) {

        // Sum of numbers 1 to 100
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;  // sum = sum + i
        }
        System.out.println("Sum 1 to 100 = " + sum); // 5050

        // Multiplication table
        int num = 7;
        System.out.println("\nTable of " + num + ":");
        for (int i = 1; i <= 10; i++) {
            System.out.println(num + " x " + i + " = " + (num * i));
        }
    }
}
▶ OUTPUT
Sum 1 to 100 = 5050 Table of 7: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
📁 ForLoop3.java
public class ForLoop3 {
    public static void main(String[] args) {

        // Optional parts demonstration
        System.out.println("--- Init outside loop ---");
        int i = 1;           // initialization bahar
        for (; i <= 3; i++) { // init part empty
            System.out.println("i = " + i);
        }

        System.out.println("\n--- Update inside body ---");
        for (int j = 1; j <= 3; ) {  // update part empty
            System.out.println("j = " + j);
            j++;             // update andar
        }

        System.out.println("\n--- Multiple init and update ---");
        for (int a = 0, b = 10; a <= b; a++, b--) {
            System.out.println("a=" + a + " b=" + b);
        }
    }
}
▶ OUTPUT
--- Init outside loop --- i = 1 i = 2 i = 3 --- Update inside body --- j = 1 j = 2 j = 3 --- Multiple init and update --- a=0 b=10 a=1 b=9 a=2 b=8 a=3 b=7 a=4 b=6 a=5 b=5
💡 For loop ke teeno parts optional hain. Multiple variables bhi use kar sakte hain comma se. a=0,b=10 — dono ek saath badhte/ghatte hain.
📁 ForLoop4.java
public class ForLoop4 {
    public static void main(String[] args) {

        // Factorial
        int  n         = 6;
        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        System.out.println(n + "! = " + factorial); // 720

        // Prime check
        int     num     = 29;
        boolean isPrime = true;
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }
        System.out.println(num + " is prime: " + isPrime);

        // Fibonacci series
        System.out.println("\nFibonacci (10 terms):");
        int a = 0, b = 1;
        for (int i = 1; i <= 10; i++) {
            System.out.print(a + " ");
            int temp = a + b;
            a = b;
            b = temp;
        }
    }
}
▶ OUTPUT
6! = 720 29 is prime: true Fibonacci (10 terms): 0 1 1 2 3 5 8 13 21 34
📁 ForLoop5.java
public class ForLoop5 {
    public static void main(String[] args) {

        // Nested for loop - Star patterns
        System.out.println("Square Pattern:");
        for (int i = 1; i <= 4; i++) {       // rows
            for (int j = 1; j <= 4; j++) {   // columns
                System.out.print("* ");
            }
            System.out.println(); // new line after each row
        }

        System.out.println("\nRight Triangle:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {  // j goes till i
                System.out.print("* ");
            }
            System.out.println();
        }

        System.out.println("\nMultiplication Table:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.printf("%4d", i * j); // formatted
            }
            System.out.println();
        }
    }
}
▶ OUTPUT
Square Pattern: * * * * * * * * * * * * * * * * Right Triangle: * * * * * * * * * * * * * * * Multiplication Table: 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
💡 Nested loop mein outer loop rows control karta hai, inner loop columns. Inner loop outer ke har ek iteration ke liye poora chalta hai.

🟢 Topic 2: while Loop

Deep Explanation:

while (condition) {
    // body
    // update zaroori warna infinite loop!
}

Flow:

condition check → TRUE  → body → update → condition check again
               → FALSE → loop skip/exit

Agar condition shuru mein hi FALSE hai:
→ Body ZERO times execute hogi!
→ while loop skipped!

Kab use karein:

✅ Jab pata nahi kitni baar chalana hai
✅ User input pe depend kare
✅ File end tak padhna ho
✅ Game loop - jab tak game over nahi
📁 WhileLoop1.java
public class WhileLoop1 {
    public static void main(String[] args) {

        // Basic while loop
        int i = 1;
        while (i <= 5) {
            System.out.println("i = " + i);
            i++;  // update zaroori! warna infinite loop
        }

        System.out.println("Loop ended, i = " + i); // i = 6

        // Zero times execution - condition pehle hi false
        int x = 10;
        System.out.println("\nCondition false from start:");
        while (x < 5) {         // 10 < 5 = FALSE
            System.out.println("This will NEVER print!");
            x++;
        }
        System.out.println("While body executed 0 times, x = " + x);
    }
}
▶ OUTPUT
i = 1 i = 2 i = 3 i = 4 i = 5 Loop ended, i = 6 Condition false from start: While body executed 0 times, x = 10
💡 while condition pehle check karta hai. Agar shuru mein hi false hai toh body ek baar bhi nahi chalegi.
📁 WhileLoop2.java
public class WhileLoop2 {
    public static void main(String[] args) {

        // Digits of a number
        int num = 12345;
        System.out.println("Digits of " + num + ":");
        while (num > 0) {
            int digit = num % 10;   // last digit
            System.out.println("Digit: " + digit);
            num = num / 10;         // remove last digit
        }

        // Sum of digits
        int number    = 9876;
        int sumDigits = 0;
        int temp      = number;
        while (temp > 0) {
            sumDigits += temp % 10;
            temp /= 10;
        }
        System.out.println("\nSum of digits of " + number + " = " + sumDigits);
    }
}
▶ OUTPUT
Digits of 12345: Digit: 5 Digit: 4 Digit: 3 Digit: 2 Digit: 1 Sum of digits of 9876 = 30
💡 num % 10 last digit nikalata hai, num / 10 last digit hatata hai. Yeh while loop ka classic use case hai jab iterations pehle se pata nahi.
📁 WhileLoop3.java
public class WhileLoop3 {
    public static void main(String[] args) {

        // Reverse a number
        int num      = 12345;
        int reversed = 0;
        int original = num;

        while (num > 0) {
            int lastDigit = num % 10;
            reversed = reversed * 10 + lastDigit;
            num /= 10;
        }
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);

        // Palindrome check
        int n = 121;
        int rev = 0, t = n;
        while (t > 0) {
            rev = rev * 10 + t % 10;
            t /= 10;
        }
        if (n == rev)
            System.out.println("\n" + n + " is Palindrome");
        else
            System.out.println("\n" + n + " is NOT Palindrome");

        // Power without Math.pow
        int  base   = 2, exp = 8;
        long result = 1;
        int  e      = exp;
        while (e > 0) {
            result *= base;
            e--;
        }
        System.out.println("\n" + base + "^" + exp + " = " + result);
    }
}
▶ OUTPUT
Original: 12345 Reversed: 54321 121 is Palindrome 2^8 = 256
📁 WhileLoop4.java
public class WhileLoop4 {
    public static void main(String[] args) {

        // Collatz Conjecture - while ka perfect use
        // Rule: even → n/2, odd → 3n+1, 1 pe stop
        int n     = 27;
        int steps = 0;
        System.out.print("Collatz: " + n);

        while (n != 1) {
            if (n % 2 == 0)
                n = n / 2;
            else
                n = 3 * n + 1;
            System.out.print(" → " + n);
            steps++;
            if (steps % 10 == 0) System.out.println(); // new line every 10
        }
        System.out.println("\nTotal steps: " + steps);

        // GCD using while
        int a = 48, b = 18;
        int x = a,  y = b;
        while (y != 0) {
            int r = x % y;
            x = y;
            y = r;
        }
        System.out.println("\nGCD of " + a + " and " + b + " = " + x);
    }
}
▶ OUTPUT
Collatz: 27 → 82 → 41 → 124 → 62 → 31 → 94 → 47 → 142 → 71 → 214 → 107 → 322 → 161 → 484 → 242 → 121 → 364 → 182 → 91 → 274 → 137 → 412 → 206 → 103 → 310 → 155 → 466 → 233 → 700 → 350 → 175 → 526 → 263 → 790 → 395 → 1186 → 593 → 1780 → 890 → 445 → 1336 → 668 → 334 → 167 → 502 → 251 → 754 → 377 → 1132 → 566 → 283 → 850 → 425 → 1276 → 638 → 319 → 958 → 479 → 1438 → 719 → 2158 → 1079 → 3238 → 1619 → 4858 → 2429 → 7288 → 3644 → 1822 → 911 → 2734 → 1367 → 4102 → 2051 → 6154 → 3077 → 9232 → 4616 → 2308 → 1154 → 577 → 1732 → 866 → 433 → 1300 → 650 → 325 → 976 → 488 → 244 → 122 → 61 → 184 → 92 → 46 → 23 → 70 → 35 → 106 → 53 → 160 → 80 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Total steps: 111 GCD of 48 and 18 = 6

🔴 Topic 3: do-while Loop

Deep Explanation:

do {
    // body - PEHLE execute hoti hai
} while (condition);  ← semicolon ZAROORI!
               ↑
         BAAD MEIN check

while vs do-while:

while:    condition → body → condition → body...
do-while: body → condition → body → condition...
          ↑
          MINIMUM EK BAAR body chalegi!

Kab use karein:

✅ Menu show karna (pehle dikhao, phir puchho continue karein?)
✅ User input validation (pehle lo, phir check karo)
✅ Game - pehle ek baar khelo, phir puchho dobara?
✅ OTP/Password - pehle enter karo, phir validate karo
📁 DoWhile1.java
public class DoWhile1 {
    public static void main(String[] args) {

        // Basic do-while
        int i = 1;
        do {
            System.out.println("i = " + i);
            i++;
        } while (i <= 5);

        System.out.println("After loop, i = " + i);

        // KEY DIFFERENCE - condition FALSE from start
        System.out.println("\n--- while (condition false) ---");
        int x = 10;
        while (x < 5) {                        // FALSE - never enters
            System.out.println("while: " + x);
        }
        System.out.println("while ran 0 times");

        System.out.println("\n--- do-while (condition false) ---");
        int y = 10;
        do {
            System.out.println("do-while: " + y); // EK BAAR chalega!
            y++;
        } while (y < 5);                          // FALSE - but already ran once
        System.out.println("do-while ran 1 time minimum!");
    }
}
▶ OUTPUT
i = 1 i = 2 i = 3 i = 4 i = 5 After loop, i = 6 --- while (condition false) --- while ran 0 times --- do-while (condition false) --- do-while: 10 do-while ran 1 time minimum!
💡 Yahi sabse important difference hai! while → 0 times bhi ho sakta hai. do-while → MINIMUM 1 baar hamesha chalega!
📁 DoWhile2.java
public class DoWhile2 {
    public static void main(String[] args) {

        // Menu system - perfect do-while use case
        // (Simulated without Scanner for online compiler)
        int[] userChoices = {1, 2, 3, 4}; // simulating user input
        int   choiceIndex = 0;
        int   choice;

        do {
            // Menu dikhao
            System.out.println("\n=== FOOD MENU ===");
            System.out.println("1. Pizza  - Rs.299");
            System.out.println("2. Burger - Rs.149");
            System.out.println("3. Pasta  - Rs.199");
            System.out.println("4. Exit");

            // User ka choice (simulated)
            choice = userChoices[choiceIndex++];
            System.out.println("Your choice: " + choice);

            switch (choice) {
                case 1: System.out.println("Pizza ordered!");  break;
                case 2: System.out.println("Burger ordered!"); break;
                case 3: System.out.println("Pasta ordered!");  break;
                case 4: System.out.println("Goodbye!");        break;
                default: System.out.println("Invalid choice!");
            }

        } while (choice != 4); // jab tak exit nahi chuna
    }
}
▶ OUTPUT
=== FOOD MENU === 1. Pizza - Rs.299 2. Burger - Rs.149 3. Pasta - Rs.199 4. Exit Your choice: 1 Pizza ordered! === FOOD MENU === 1. Pizza - Rs.299 2. Burger - Rs.149 3. Pasta - Rs.199 4. Exit Your choice: 2 Burger ordered! === FOOD MENU === 1. Pizza - Rs.299 2. Burger - Rs.149 3. Pasta - Rs.199 4. Exit Your choice: 3 Pasta ordered! === FOOD MENU === 1. Pizza - Rs.299 2. Burger - Rs.149 3. Pasta - Rs.199 4. Exit Your choice: 4 Goodbye!
📁 DoWhile3.java
public class DoWhile3 {
    public static void main(String[] args) {

        // Password validation simulation
        String   correctPassword = "java123";
        String[] attempts        = {"hello", "pass", "java123"}; // simulated
        int      attemptIndex    = 0;
        int      maxAttempts     = 3;
        int      attemptsUsed    = 0;
        boolean  success         = false;

        do {
            String entered = attempts[attemptIndex++];
            attemptsUsed++;
            System.out.println("Attempt " + attemptsUsed + ": " + entered);

            if (entered.equals(correctPassword)) {
                success = true;
                System.out.println("Password correct! Login successful!");
            } else {
                System.out.println("Wrong password! " +
                    (maxAttempts - attemptsUsed) + " attempts left");
            }

        } while (!success && attemptsUsed < maxAttempts);

        if (!success) {
            System.out.println("Account locked after " + attemptsUsed + " attempts!");
        }
    }
}
▶ OUTPUT
Attempt 1: hello Wrong password! 2 attempts left Attempt 2: pass Wrong password! 1 attempts left Attempt 3: java123 Password correct! Login successful!
📁 DoWhile4.java
public class DoWhile4 {
    public static void main(String[] args) {

        // Number guessing game simulation
        int   secretNumber = 42;
        int[] guesses      = {10, 70, 42}; // simulated guesses
        int   guessIndex   = 0;
        int   guess;
        int   attempts     = 0;

        System.out.println("=== Number Guessing Game ===");
        System.out.println("Guess a number between 1-100");

        do {
            guess = guesses[guessIndex++];
            attempts++;
            System.out.println("\nGuess #" + attempts + ": " + guess);

            if      (guess < secretNumber)
                System.out.println("Too LOW! Go higher");
            else if (guess > secretNumber)
                System.out.println("Too HIGH! Go lower");
            else
                System.out.println("CORRECT! You got it!");

        } while (guess != secretNumber);

        System.out.println("Total attempts: " + attempts);
    }
}
▶ OUTPUT
=== Number Guessing Game === Guess a number between 1-100 Guess #1: 10 Too LOW! Go higher Guess #2: 70 Too HIGH! Go lower Guess #3: 42 CORRECT! You got it! Total attempts: 3

🟡 Topic 4: for-each Loop

Deep Explanation:

for (dataType element : arrayOrCollection) {
    // element use karo
}

Normal for vs for-each:

// Normal for:
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);  // index se access
}

// for-each:
for (int num : arr) {
    System.out.println(num);     // directly element
}

Important Rules:

✅ Array aur Collection traverse ke liye
✅ Read-only access - simple aur clean
❌ Element modify karna array ko affect NAHI karta
❌ Index access nahi milta
❌ Reverse traverse nahi kar sakte
❌ Skip nahi kar sakte (every element visit hoga)
📁 ForEach1.java
public class ForEach1 {
    public static void main(String[] args) {

        // Basic for-each with array
        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Using for-each:");
        for (int num : numbers) {
            System.out.println("num = " + num);
        }

        // String array
        String[] fruits = {"Apple", "Banana", "Mango", "Orange"};
        System.out.println("\nFruits:");
        for (String fruit : fruits) {
            System.out.println("→ " + fruit);
        }

        // Sum using for-each
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("\nSum = " + sum);
    }
}
▶ OUTPUT
Using for-each: num = 10 num = 20 num = 30 num = 40 num = 50 Fruits: → Apple → Banana → Mango → Orange Sum = 150
📁 ForEach2.java
public class ForEach2 {
    public static void main(String[] args) {

        // IMPORTANT: for-each mein modify karna array affect NAHI karta!
        int[] arr = {1, 2, 3, 4, 5};

        System.out.println("Before modification:");
        for (int n : arr) {
            System.out.print(n + " ");
        }

        // array modify karne ki koshish
        for (int n : arr) {
            n = n * 10;  // sirf local copy badla, array nahi!
        }

        System.out.println("\nAfter 'modification' with for-each:");
        for (int n : arr) {
            System.out.print(n + " "); // original values!
        }

        // Sahi tarika - normal for loop se modify karo
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 10;  // actual array modify hoga
        }

        System.out.println("\nAfter actual modification (normal for):");
        for (int n : arr) {
            System.out.print(n + " ");
        }
    }
}
▶ OUTPUT
Before modification: 1 2 3 4 5 After 'modification' with for-each: 1 2 3 4 5 After actual modification (normal for): 10 20 30 40 50
💡 for-each mein n ek copy hai array element ki. n ko change karo, array nahi badlega! Array modify karna ho toh normal for loop use karo with index.
📁 ForEach3.java
public class ForEach3 {
    public static void main(String[] args) {

        // 2D array with for-each
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        System.out.println("2D Array:");
        for (int[] row : matrix) {         // outer: each row
            for (int elem : row) {         // inner: each element
                System.out.printf("%4d", elem);
            }
            System.out.println();
        }

        // Find max in array
        int[] scores = {45, 89, 23, 67, 91, 34, 78};
        int   max    = scores[0];
        for (int score : scores) {
            if (score > max) max = score;
        }
        System.out.println("\nScores: ");
        for (int s : scores) System.out.print(s + " ");
        System.out.println("\nMax Score: " + max);
    }
}
▶ OUTPUT
2D Array: 1 2 3 4 5 6 7 8 9 Scores: 45 89 23 67 91 34 78 Max Score: 91
📁 ForEach4.java
public class ForEach4 {
    public static void main(String[] args) {

        int[] arr = {5, 3, 8, 1, 9, 2, 7};

        // for-each: READ only kaam - clean & simple
        System.out.println("for-each (read only):");
        int total = 0;
        for (int n : arr) {
            total += n;
        }
        System.out.println("Total = " + total);

        // Normal for: index chahiye
        System.out.println("\nNormal for (with index):");
        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr[" + i + "] = " + arr[i]);
        }

        // Count even numbers
        int evenCount = 0;
        for (int n : arr) {
            if (n % 2 == 0) evenCount++;
        }
        System.out.println("\nEven count: " + evenCount);

        // char array
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        System.out.println("\nVowels:");
        for (char v : vowels) {
            System.out.print(v + " ");
        }
    }
}
▶ OUTPUT
for-each (read only): Total = 35 Normal for (with index): arr[0] = 5 arr[1] = 3 arr[2] = 8 arr[3] = 1 arr[4] = 9 arr[5] = 2 arr[6] = 7 Even count: 2 Vowels: a e i o u

⚡ Topic 5: break aur continue

Deep Explanation:

break    → loop se BAHAR niklo abhi!
continue → is iteration SKIP karo, agli pe jao

break:

for(i=1 to 10) {
    if(i==5) break; ← loop khatam, i=5 pe
    print(i)
}
// Output: 1 2 3 4

continue:

for(i=1 to 5) {
    if(i==3) continue; ← sirf i=3 skip
    print(i)
}
// Output: 1 2 4 5
📁 BreakContinue1.java
public class BreakContinue1 {
    public static void main(String[] args) {

        // break - loop se bahar niklo
        System.out.println("--- break demo ---");
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                System.out.println("Break at i=" + i);
                break;  // loop khatam
            }
            System.out.print(i + " ");
        }

        System.out.println("\n\n--- continue demo ---");
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;  // even numbers skip
            }
            System.out.print(i + " "); // sirf odd print
        }

        // break in while
        System.out.println("\n\n--- break in while ---");
        int n = 1;
        while (true) {        // infinite loop
            System.out.print(n + " ");
            if (n == 5) break; // yahan se bahar
            n++;
        }
    }
}
▶ OUTPUT
--- break demo --- 1 2 3 4 5 Break at i=6 --- continue demo --- 1 3 5 7 9 --- break in while --- 1 2 3 4 5

🏷️ Topic 6: Labelled break/continue IMPORTANT!

Deep Explanation: Normal break/continue sirf inner loop ko affect karta hai!

outer:                    ← label
for(int i=0; i<3; i++) {
    for(int j=0; j<3; j++) {
        if(j==1) break outer; ← OUTER loop band!
    }
}

Without label:

break    → sirf inner loop band
continue → sirf inner loop ki current iteration skip

With label:

break outerLabel    → outer loop band
continue outerLabel → outer loop ki current iteration skip
📁 LabelledLoop1.java
public class LabelledLoop1 {
    public static void main(String[] args) {

        // Normal break - sirf inner loop
        System.out.println("--- Normal break (inner only) ---");
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) break; // sirf inner loop band
                System.out.println("i=" + i + " j=" + j);
            }
        }

        // Labelled break - outer loop bhi band
        System.out.println("\n--- Labelled break (outer too) ---");
        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) break outer; // OUTER loop band!
                System.out.println("i=" + i + " j=" + j);
            }
        }
        // sirf i=1,j=1 print hoga phir outer loop band!
    }
}
▶ OUTPUT
--- Normal break (inner only) --- i=1 j=1 i=2 j=1 i=3 j=1 --- Labelled break (outer too) --- i=1 j=1
💡 Normal break → inner loop 3 baar chala (har baar j=1 pe stop). Labelled break → poora outer loop pehli baar i=1, j=2 pe band ho gaya!
📁 LabelledLoop2.java
public class LabelledLoop2 {
    public static void main(String[] args) {

        // Labelled continue
        System.out.println("--- Normal continue ---");
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) continue; // inner j=2 skip
                System.out.println("i=" + i + " j=" + j);
            }
        }
        // j=2 wali lines skip hongi but loop chalta rahega

        System.out.println("\n--- Labelled continue ---");
        outer:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) continue outer; // OUTER next iteration!
                System.out.println("i=" + i + " j=" + j);
            }
        }
        // j=2 aate hi outer loop next i pe jump karega
        // j=3 kabhi nahi chalega!
    }
}
▶ OUTPUT
--- Normal continue --- i=1 j=1 i=1 j=3 i=2 j=1 i=2 j=3 i=3 j=1 i=3 j=3 --- Labelled continue --- i=1 j=1 i=2 j=1 i=3 j=1
💡 Normal continue → j=2 skip, j=3 chalega. Labelled continue → j=2 pe outer loop ka next iteration start, j=3 kabhi nahi chalega!
📁 LabelledLoop3.java
public class LabelledLoop3 {
    public static void main(String[] args) {

        // Real use: 2D array mein search
        int[][] grid = {
            { 1,  2,  3,  4},
            { 5,  6,  7,  8},
            { 9, 10, 42, 12}  // 42 yahan hai
        };

        int     target = 42;
        boolean found  = false;

        System.out.println("Searching for " + target + " in grid:");

        search:                                  // label
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                System.out.print("Checking ["+i+"]["+j+"]="+grid[i][j]+"  ");
                if (grid[i][j] == target) {
                    System.out.println("\nFound " + target +
                        " at position [" + i + "][" + j + "]");
                    found = true;
                    break search;               // dono loops band!
                }
            }
            System.out.println();
        }

        if (!found) System.out.println("Not found!");
    }
}
▶ OUTPUT
Searching for 42 in grid: Checking [0][0]=1 Checking [0][1]=2 Checking [0][2]=3 Checking [0][3]=4 Checking [1][0]=5 Checking [1][1]=6 Checking [1][2]=7 Checking [1][3]=8 Checking [2][0]=9 Checking [2][1]=10 Checking [2][2]=42 Found 42 at position [2][2]

🚫 Topic 7: Infinite Loop aur Unreachable Code

📁 InfiniteLoop1.java
public class InfiniteLoop1 {
    public static void main(String[] args) {

        // Infinite loop types
        // for(;;) { }          // ← teeno parts empty
        // while(true) { }      // ← always true
        // do { } while(true);  // ← always true

        // Controlled infinite loop with break
        int count = 0;
        for (;;) {              // infinite loop
            count++;
            System.out.println("Count: " + count);
            if (count == 5) {
                System.out.println("Breaking out!");
                break;          // yahan se bahar
            }
        }

        // Unreachable code - compiler error deta hai
        // for(;;) {
        //     System.out.println("infinite");
        // }
        // System.out.println("unreachable!"); // ← ERROR!
        // ISLIYE yeh comment kar diya

        System.out.println("Program ended normally");
    }
}
▶ OUTPUT
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Breaking out! Program ended normally
💡 Infinite loop ke baad kuch likhne par Unreachable Code compiler error deta hai — compiler jaanta hai woh line kabhi execute nahi hogi. break se controlled exit karo.

📋 Complete Revision Summary

Loop TypeKey Points
for Jab iterations pata ho  |  init ; condition ; update  |  Teeno parts optional — for(;;) = infinite
while Condition-based, pehle check  |  Condition false → 0 times execute  |  Update body mein karo
do-while Body PEHLE, condition BAAD  |  MINIMUM 1 baar hamesha chalega!  |  while ke baad semicolon ZAROORI
for-each Array/Collection traverse  |  Read-only — modify array affect NAHI  |  Index access nahi milta

⭐ Important Points — Exam Sheet

✅ for(;;) → infinite loop (teeno parts empty)
✅ while condition → FALSE se start? → 0 times execute
✅ do-while → MINIMUM 1 baar hamesha!
✅ for-each modify → array NAHI badlega (local copy)
✅ break → loop se bahar
✅ continue → current iteration skip
✅ Labelled break → outer loop bhi band
✅ Labelled continue→ outer loop next iteration
❌ Infinite loop baad → unreachable code = compiler ERROR
❌ Nested loop break → sirf inner loop affect (label use karo)

⚠️ Common Mistakes

MistakeWrong ❌Right ✅
do-while semicolon} while(x<5)} while(x<5);
for-each modifyfor(int n:arr) n*=2Use normal for with index
Infinite loopForgetting update in whileAlways update variable
Break scopeThinking break exits outerUse labelled break
Unreachable codeCode after infinite loopAdd break before that code
🏆 Golden Rule File name = Class name exactly! Jaise class ForLoop1 hai toh file ForLoop1.java hogi!