Loops
Comparison of Loops
Feature | for Loop | while Loop | do-while Loop | Enhanced for Loop |
---|---|---|---|---|
Condition Check | Before each iteration | Before each iteration | After each iteration | N/A (Iterates through each element) |
Usage | Known number of iterations | Unknown iterations with a condition | At least one execution is required | Iterating over arrays/collections |
Best For | Counting loops | Conditional loops | Loops requiring at least one pass | Arrays/Collections |
1. What Are Loops?
Loops are control structures that allow a block of code to be executed repeatedly until a specified condition is met.
2. Types of Loops in Java
- for Loop
- while Loop
- do-while Loop
- Enhanced for Loop (for-each Loop)
3. for Loop
The for
loop is used when the number of iterations is known beforehand.
Syntax
for (initialization; condition; update) {
// Code to be executed in each iteration
}
Example
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
Working
- Initialization: Executes once before the loop starts (e.g.,
int i = 1
). - Condition: Checked before each iteration. If
true
, the loop runs; iffalse
, the loop exits. - Update: Executes after each iteration (e.g.,
i++
).
4. while Loop
The while
loop is used when the number of iterations is not known and depends on a condition.
Syntax
while (condition) {
// Code to be executed
}
Example
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
Working
- The condition is checked before each iteration.
- If the condition is
true
, the loop body executes. - If the condition is
false
, the loop terminates.
5. do-while Loop
The do-while
loop is similar to the while
loop, but it ensures that the loop body executes at least once before the condition is checked.
Syntax
do {
// Code to be executed
} while (condition);
Example
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
Working
- Executes the loop body first.
- Then checks the condition.
- Repeats the process if the condition is
true
.
6. Enhanced for Loop (for-each Loop)
The enhanced for
loop is used to iterate over arrays or collections.
Syntax
for (type variable : arrayOrCollection) {
// Code to execute for each element
}
Example
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
Working
- Iterates through each element in the array or collection.
- Assigns each element to the loop variable (
num
in the example).
Control Statements in Loops
Java provides additional control statements to manage the flow of loops:
1. break
- Terminates the loop immediately.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit loop when i equals 3
}
System.out.println(i);
}
2. continue
- Skips the current iteration and moves to the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the code for i = 3
}
System.out.println(i);
}
3. return
- Exits from the current method entirely, stopping all loops.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
return; // Exits the method
}
System.out.println(i);
}
Examples of Nested Loops
Loops can be nested inside one another for multidimensional iterations.
Example: Nested for Loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
Infinite Loops
An infinite loop occurs when the termination condition is never met.
Example
while (true) {
System.out.println("This is an infinite loop.");
}
Use break
to terminate infinite loops when needed.
Best Practices for Loops
- Avoid Infinite Loops: Ensure the condition eventually becomes
false
. - Optimize Performance: Minimize operations inside the loop.
- Use Enhanced
for
: When iterating over arrays/collections. - Clear Conditions: Ensure loop conditions are readable and maintainable.