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.

Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the
loop terminates.

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.

Java Do While loop – Questions and Answers

Q 1: What is do-while loop?

Ans: A loop that executes at least once.

Q 2: Is do-while entry or exit-controlled?

Ans: Exit-controlled loop.

Q 3: When is condition checked in do-while?

Ans: After executing loop body.

Q 4: Can do-while run without condition?

Ans: No, condition is mandatory.

Q 5: Where is do-while commonly used?

Ans: Menu-driven programs.

Java Do While Loop – Objective Questions (MCQs)

Q1. Which of the following is the correct syntax for a do-while loop in Java?






Q2. What is the key difference between a while loop and a do-while loop?






Q3. What will be the output of the following code?

int int i = 1;
do {
System.out.print(i + ' ');
i++;
} while (i <= 3);






Q4. What will be the output of the following code?

int x = 10;
do {
System.out.println("Hello");
} while (x < 5);






Q5. How many times will this loop execute?

int n = 5;
do {
n++;
} while (n < 5);






Related Java Do While Loop Topics