🔄 What Are Loops?
Loops are fundamental in Java for repeating code blocks efficiently. They allow you to execute a set of instructions multiple times until a specific condition is met.
🧮 For Loop
The for
loop is ideal for iterating over a known range or array.
Syntax:
for (initialization; condition; increment) {
// code to execute
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
Use Cases:
- Iterating through arrays
- Repeating actions a fixed number of times
- Counting or summing values
⏳ While Loop
The while
loop executes as long as a condition is true.
Syntax:
while (condition) {
// code to execute
}
Example:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
Use Cases:
- Repeating until a user inputs valid data
- Iterating through a list with unknown length
- Implementing game loops or event-driven logic
🔁 Do-While Loop
The do-while
loop ensures the code block runs at least once before checking the condition.
Syntax:
do {
// code to execute
} while (condition);
Example:
int i = 0;
do {
System.out.println("Do-While Iteration: " + i);
i++;
} while (i < 5);
Use Cases:
- Validating user input (e.g., password confirmation)
- Menu systems where user interaction is required
- Situations needing guaranteed initial execution
🧩 Practice & Extend
Try writing a loop to calculate the sum of numbers from 1 to 10!
For deeper understanding, explore our guide on Java Control Flow.
Note: All images and links are illustrative. For actual learning, refer to official Java documentation or coding platforms.