Explain Loop in Java with suitable example

Loop in Java

Loop in Java – loop structures are used to repeat a block of code multiple times. Java provides three primary types of loops:

  • For loop
  • While loop
  • Do-While loop

For Loop in Java

The for loop in Java is used when you know in advance how many times you want to execute a statement or a block of statements.

Syntax

for (initialization; condition; update) {
    // statements
}

Example

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

While Loop in Java

The while loop in Java is used when you want to execute a statement or a block of statements as long as a condition is true.

Syntax:

while (condition) {
    // statements
}

Example of while loop in Java:

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 0;
        while (i < 5) {
            System.out.println("Iteration: " + i);
            i++;
        }
    }
}

Do-While Loop in Java

The do-while loop in Java is similar to the while loop, but it guarantees that the loop will execute at least once.

Syntax:

do {
    // statements
} while (condition);

Example:

public class DoWhileLoopExample {
    public static void main(String[] args) {
        int i = 0;
        do {
            System.out.println("Iteration: " + i);
            i++;
        } while (i < 5);
    }
}

Summary

  • Use a for loop when you know the exact number of iterations.
  • Use a while loop when the number of iterations is not known, and you want to continue looping while a condition is true.
  • Use a do-while loop when you need to ensure that the loop executes at least once.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *