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
loopis 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-whileloop run if the condition is false from the start?' Answer: Exactly once. It checks the condition only after the first run."
π‘ Pro Tip: "Use
forwhen you count,whilewhen you wait. Choosing the right loop makes your code much easier to read!" - Vishnu Damwala