Do-While Loop in Java | Control Flow in Java

The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a boolean condition, but it guarantees that the loop's body will be executed at least once. This makes it useful for scenarios where you want to ensure at least one iteration occurs.

Key Points on Do-While Loop:

Syntax of Do-While Loop:

Syntax Example

do {
    // Code to execute in each iteration
} while (condition);

Example of Do-While Loop in Java:

This example demonstrates a basic do-while loop that prints numbers from 1 to 5.

Code Example 1

public class PrintNumbersDoWhile {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++; // Increment the loop variable
        } while (i <= 5);
    }
}

Output for Code Example 1:

1
2
3
4
5

Using Control Statements:

This example shows how to use the break statement in a do-while loop.

Code Example 2

public class BreakDoWhileExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            if (i == 5) {
                break; // Exit the loop when i equals 5
            }
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

Output for Code Example 2:

1
2
3
4

Example of a Do-While Loop with Condition Change:

This example uses a do-while loop to sum numbers until a certain limit is reached.

Code Example 3

public class SumDoWhileExample {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1;
        do {
            sum += i; // Add i to sum
            i++; // Increment i
        } while (i <= 5);
        System.out.println("Sum: " + sum);
    }
}

Output for Code Example 3:

Sum: 15

Detailed Explanation:

By mastering the do-while loop, developers can ensure that certain code runs at least once while still maintaining control over the flow of their Java programs.