A loop is a structure that allows you to repeat a block of code over and over again as long as a specific condition is true. Once that condition becomes false, the loop "breaks," and the program moves on.
In Java, there are three main types of loops. Think of them as different tools for different repetitive tasks.
The 3 Main Types of Loops
1. The for Loop (The "Counter")
Use this when you know exactly how many times you want to repeat something (e.g., "Do this 10 times").
Syntax:
for (initialization; condition; increment)It sets a starting point, checks if it should keep going, and updates the counter after every lap.
2. The while Loop (The "Condition Watcher")
Use this when you don't know the exact count, but you know under what condition to keep going (e.g., "Keep playing the game until the player hits 'Quit'").
It checks the condition before running the code inside.
3. The do-while Loop (The "Guaranteed Lap")
This is similar to the while loop, but it checks the condition after running the code.
Crucial Difference: A
do-whileloop will always run at least once, even if the condition is false from the start.
The Code Example:
public class LoopsDemo {
public static void main(String[] args) {
System.out.println("--- 1. The 'for' Loop (Counting to 3) ---");
for (int i = 1; i <= 3; i++) {
System.out.println("Lap number: " + i);
}
System.out.println("\n--- 2. The 'while' Loop (Countdown) ---");
int energy = 3;
while (energy > 0) {
System.out.println("Robot is moving... Energy left: " + energy);
energy--; // Decreasing energy so the loop eventually ends
}
System.out.println("Robot out of battery!");
System.out.println("\n--- 3. The 'do-while' Loop (Try once) ---");
int attempts = 0;
do {
System.out.println("Attempting to connect to server...");
attempts++;
} while (attempts < 1); // Even if this was false, it runs once!
}
}Expected Output:
--- 1. The 'for' Loop (Counting to 3) ---
Lap number: 1
Lap number: 2
Lap number: 3
--- 2. The 'while' Loop (Countdown) ---
Robot is moving... Energy left: 3
Robot is moving... Energy left: 2
Robot is moving... Energy left: 1
Robot out of battery!
--- 3. The 'do-while' Loop (Try once) ---
Attempting to connect to server...Loops are everywhere. Every time you scroll through a list of photos on Instagram, a loop is rendering those images. Every time a game checks if your character is still touching the ground, a loop is running.
Warning: The Infinite Loop! If you write a loop where the condition never becomes false (e.g., you forget to do
energy--), the program will run forever and might crash your computer. Always make sure your loop has an "exit strategy."