Loop in Java Programming

Loops are control structures that enable you to iterate over a block of code until a certain condition is met. They eliminate the need for writing repetitive code, making programs more efficient and concise. Loops play a vital role in handling collections of data, performing calculations, and implementing iterative algorithms.

Types of Loops in Java

Java provides three main types of loops: the for loop, the while loop, and the do-while loop. Each loop type has its own specific use cases and syntax. Let's explore each type in detail.

for Loop

The for loop is a compact and powerful construct for iteration. It consists of three parts: initialization, condition, and iteration expression. The loop continues until the condition evaluates to false.

Syntax
for (initialization; condition; iteration) {
    // code to be executed
}
Example
public class ForLoopSmallCode {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

while Loop

The while loop repeatedly executes a block of code as long as the specified condition is true. The condition is evaluated before entering the loop body.

Syntax
while (condition) {
    // code to be executed
    // iteration or condition update
}
Example
public class WhileLoopSmallCode {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
    }
}

do-while Loop

The do-while loop is similar to the while loop, but the condition is evaluated after executing the loop body. This guarantees that the loop body is executed at least once.

Syntax
do {
    // code to be executed
    // iteration or condition update
} while (condition);
Example
public class DoWhileLoopSmallCode {
    public static void main(String[] args) {
        int num = 1;

        do {
            System.out.println("Number: " + num);
            num++;
        } while (num <= 5);
    }
}
Note

Loops are indispensable tools in Java programming, providing the ability to repeat code execution based on specific conditions. The for loop is suitable for iterating over a known number of times, while the while and do-while loops are more flexible when the exact number of iterations is unknown.