Java Do While loop

In Java, a do-while loop is used to execute a block of code repeatedly as long as a specified condition is true. The key difference between a do-while loop and a while loop is that in a do-while loop, the condition is evaluated after the execution of the code block, ensuring that the code block runs at least once.

Syntax:


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

Explanations:

do: Marks the start of the loop.

Code block: The code inside the do block is executed once before the condition is checked.

while (condition): After executing the code, the loop checks the condition. If the condition is true, the loop will continue to execute. If it is false, the loop will terminate.

Example:


public class Example1 {
    public static void main(String[] args) {
        int count = 1;

        // Do-while loop to print numbers from 1 to 5
        do {
            System.out.println("Count: " + count);
            count++; // Increment count
        } while (count <= 5);
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Code Explanation:

1. The code block inside the do statement will execute at least once, even if the condition (count <= 5) is initially false.

2. After the first execution, the condition is checked. If the condition is true, the loop will repeat.

3. The loop continues to execute until the condition becomes false.

Important Points:

1. The loop will always execute at least once, even if the condition is false initially.

2. If the condition is false on the first iteration, the loop will execute once and then terminate.