3.3. Loops
Loops are fundamental constructs in Java that allow you to execute a block of code repeatedly based on a condition. They are essential for tasks that require iteration, such as processing arrays or performing repetitive calculations.
Types of Loops in Java
Java provides several types of loops:
for
Loop: Used when the number of iterations is known beforehand.while
Loop: Used when the number of iterations depends on a condition.do-while
Loop: Similar to thewhile
loop, but guarantees at least one execution of the loop body.
for
Loop
The for
loop is ideal for iterating a specific number of times.
Syntax:
for (initialization; condition; update) {
// Code to execute in each iteration
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
In this example:
int i = 0
: Initializes the loop variable.i < 5
: The loop continues as long as this condition is true.i++
: Updates the loop variable after each iteration.
while
Loop
The while
loop is used when the number of iterations depends on a condition.
Syntax:
while (condition) {
// Code to execute while condition is true
}
Example:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
In this example, the loop runs as long as count < 3
.
do-while
Loop
The do-while
loop ensures the loop body executes at least once, even if the condition is false.
Syntax:
do {
// Code to execute
} while (condition);
Example:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 3);
Enhanced for
Loop (For-Each)
The enhanced for
loop is used to iterate over arrays or collections.
Syntax:
for (type element : collection) {
// Code to execute for each element
}
Example:
int[] numbers = {1, 2, 3, 4};
for (int num : numbers) {
System.out.println("Number: " + num);
}
Nested Loops
Loops can be nested to handle multi-dimensional data or complex tasks.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
Infinite Loops
An infinite loop occurs when the termination condition is never met. Use them cautiously.
Example:
while (true) {
System.out.println("This is an infinite loop.");
}
Common Pitfalls and Best Practices
- Off-by-One Errors: Ensure loop boundaries are correct.
- Infinite Loops: Always verify the termination condition.
- Readability: Keep loop logic simple and clear.
Example Code Snippet
public class LoopExamples {
public static void main(String[] args) {
// For loop example
for (int i = 1; i <= 5; i++) {
System.out.println("Square of " + i + ": " + (i * i));
}
// While loop example
int num = 1;
while (num <= 3) {
System.out.println("Number: " + num);
num++;
}
// Do-while loop example
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 2);
// Nested loop example
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
}
}