Skip to content

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:

  1. for Loop: Used when the number of iterations is known beforehand.
  2. while Loop: Used when the number of iterations depends on a condition.
  3. do-while Loop: Similar to the while 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:

java
for (initialization; condition; update) {
    // Code to execute in each iteration
}

Example:

java
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:

java
while (condition) {
    // Code to execute while condition is true
}

Example:

java
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:

java
do {
    // Code to execute
} while (condition);

Example:

java
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:

java
for (type element : collection) {
    // Code to execute for each element
}

Example:

java
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:

java
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:

java
while (true) {
    System.out.println("This is an infinite loop.");
}

Common Pitfalls and Best Practices

  1. Off-by-One Errors: Ensure loop boundaries are correct.
  2. Infinite Loops: Always verify the termination condition.
  3. Readability: Keep loop logic simple and clear.

Example Code Snippet

java
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);
            }
        }
    }
}