java

Java Loops


What is Loop?

Loop is nothing but repetition of certain statements several times as long as a specified condition is true.

Java provides several types of loops,

1. for loop

Syntax

for (initialization; condition; update) {
    // code to be repeated
}

 

Example

public class ForLoop {
    public static void main(String[] args) {
        // Using a for loop to print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println("Number: " + i);
        }
    }
}

 

2. while loop

Syntax

while (condition) {
    // code to be repeated
}

 

Example

public class WhileLoop {
    public static void main(String[] args) {
        // Using a while loop to print numbers from 1 to 5
        int i = 1; // Initialization
        while (i <= 5) { // Condition
            System.out.println("Number: " + i);
            i++; // Updating the value
        }
    }
}

 

3. do while loop

Syntax

do {
    // code to be repeated
} while (condition);

 

Example

public class DoWhileLoop {
    public static void main(String[] args) {
        // Using a do-while loop to print numbers from 1 to 5
        int i = 1; // Initialization
        do {
            System.out.println("Number: " + i);
            i++; // Update
        } while (i <= 5); // Condition
    }
}

 

4. for-each loop

Syntax

for (elementType element : arrayOrCollection) {
    // code to be executed for each element
}

 

Example

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

        // Using a for-each loop to iterate over the elements in the array
        for (int num : numbers) {
            System.out.println("Number: " + num);
        }
    }
}