Looping statements in Java are used to execute a block of code repeatedly, either for a fixed number of iterations or until a specified condition is met. Java provides several types of loops to handle various scenarios.
1. while Loop
- Purpose: Repeats a block of code while a condition is true.
- Syntax:
while (condition) {
// Code to be executed
}
- Key Points:
- The condition is evaluated before each iteration.
- If the condition is false initially, the loop body will not execute.
Example:
public class WhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(“Iteration: ” + i);
i++;
}
}
}
2. do-while Loop
- Purpose: Executes a block of code at least once, then repeats while the condition is true.
- Syntax:
do {
// Code to be executed
} while (condition);
- Key Points:
- The condition is evaluated after executing the loop body.
- Useful when the loop body must execute at least once.
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(“Iteration: ” + i);
i++;
} while (i <= 5);
}
}
3. for Loop
- Purpose: Used when the number of iterations is known in advance.
- Syntax:
for (initialization; condition; update) {
// Code to be executed
}
- Key Points:
- Combines initialization, condition checking, and update in a single line.
- Suitable for iterating over ranges or arrays.
Example:
public class ForExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(“Iteration: ” + i);
}
}
}
4. Enhanced for Loop (For-Each Loop)
- Purpose: Simplifies iteration over arrays or collections.
- Syntax:
for (type variable : array/collection) {
// Code to be executed
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(“Number: ” + num);
}
}
}
5. Nested Loops
- Purpose: Loops inside loops, useful for working with multidimensional arrays or repetitive structures.
- Key Points:
- Inner loop executes completely for each iteration of the outer loop.
- Be cautious of performance as nesting can lead to high complexity.
Example:
public class NestedLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(“i: ” + i + “, j: ” + j);
}
}
}
}
Break and Continue Statements
- Break: Exits the current loop immediately.
- Continue: Skips the remaining code in the current iteration and proceeds to the next iteration.
Example with break:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i is 3
}
System.out.println(“Iteration: ” + i);
}
}
}
Example with continue:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the code when i is 3
}
System.out.println(“Iteration: ” + i);
}
}
}
Comparison of Loops
Feature | while | do-while | for | Enhanced for (For-Each) |
Condition Check | Before execution | After execution | Before execution | Implicit (iterates over elements) |
Use Case | Indeterminate loops | At least one iteration | Known number of iterations | Arrays/Collections |
Initialization | Outside loop | Outside loop | Combined in syntax | Automatic |
Best Practices
- Choose the Right Loop:
- Use for loops for fixed iterations.
- Use while or do-while for condition-based loops.
- Use enhanced for loops for arrays or collections.
- Avoid Infinite Loops:
- Ensure the condition eventually becomes false.
- Example of infinite loop:
while (true) {
System.out.println(“This will run forever!”);
}
- Minimize Nested Loops:
- Keep nesting to a minimum to avoid performance issues.
- Refactor code for readability and efficiency when nesting is complex.
- Use Comments:
- Document the purpose of loops, especially nested ones, to improve maintainability.