Skip to content

Loops

In Java, loops are used to execute a block of code repeatedly based on a given condition. Java provides several types of loops to handle different looping scenarios. The main types of loops in Java are:

  1. For Loop
  2. While Loop
  3. Do-While Loop
  4. Enhanced For Loop (for-each loop)

Let’s explore each of them in detail.

1. For Loop

The for loop is used when you know in advance how many times you want to execute a statement or a block of statements. It consists of three parts:

  • Initialization: Sets up the loop variable.
  • Condition: The condition that needs to be true for the loop to continue running.
  • Update: Increments or decrements the loop variable after each iteration.

Syntax:

java
for (initialization; condition; update) {
    // Code to be executed
}

Example:

java
public class ForLoopExample {
    public static void main(String[] args) {
        // Print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}
  • Initialization: int i = 1 (set the starting point).
  • Condition: i <= 5 (loop runs while i is less than or equal to 5).
  • Update: i++ (increment i by 1 after each iteration).

2. While Loop

The while loop is used when you want to execute a block of code as long as a condition is true. The condition is checked before the execution of the code inside the loop.

Syntax:

java
while (condition) {
    // Code to be executed
}

Example:

java
public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++; // Increment to avoid infinite loop
        }
    }
}
  • The loop runs as long as i <= 5.
  • Important: Be careful with the condition inside a while loop. If it is never false, it can lead to an infinite loop.

3. Do-While Loop

The do-while loop is similar to the while loop, but with a key difference: it guarantees that the code inside the loop will run at least once, even if the condition is false initially. The condition is checked after executing the loop body.

Syntax:

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

Example:

java
public class DoWhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++; // Increment to avoid infinite loop
        } while (i <= 5);
    }
}
  • The loop will run at least once even if the condition (i <= 5) is false initially.

4. Enhanced For Loop (for-each loop)

The enhanced for loop (also known as the for-each loop) is a simplified version of the for loop that is primarily used to iterate through collections like arrays or other iterable data structures. It automatically iterates through each element in the collection, without needing an explicit counter variable.

Syntax:

java
for (type variable : collection) {
    // Code to be executed for each element
}

Example:

java
public class EnhancedForLoopExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int num : numbers) {
            System.out.println(num);  // Print each number in the array
        }
    }
}
  • int num: The variable that holds each element in the array during each iteration.
  • numbers: The array to be iterated over.

The enhanced for loop is particularly useful for iterating through arrays or other collections like ArrayLists, HashSets, etc.


Loop Control Statements

Java also provides several loop control statements that allow you to control the flow of loops:

  1. break: Exits the loop entirely, regardless of the condition.
  2. continue: Skips the current iteration and moves to the next iteration of the loop.
  3. return: Exits the entire method, not just the loop.

Example of break:

java
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 equals 3
            }
            System.out.println(i);
        }
    }
}
  • The loop will print 1, 2, and then stop because of the break statement when i equals 3.

Example of continue:

java
public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;  // Skip this iteration when i equals 3
            }
            System.out.println(i);
        }
    }
}
  • The loop will print 1, 2, 4, 5 (skipping 3).

Summary of Loops:

  • For Loop: Best for when you know exactly how many times you want to repeat an action.
  • While Loop: Best for when you want to repeat an action until a condition becomes false.
  • Do-While Loop: Best when you want the code to run at least once before checking the condition.
  • Enhanced For Loop: Best for iterating over arrays or collections without needing an index variable.

Loops are fundamental to Java programming and allow you to write efficient and repeatable code. By using the appropriate type of loop based on the problem you're solving, you can avoid redundancy and make your code more readable.

J2J Institute private limited