Do-While Loop

The do-while loop in Java is a type of control flow statement used to execute a block of code repeatedly based on a condition. The key difference between the do-while loop and other loops (like for and while) is that the condition is checked after the execution of the code block, ensuring that the code inside the loop is always executed at least once.

Syntax

  • The loop executes the statement(s) inside the block first before checking the condition.
  • It ensures that the code inside the loop is executed at least once, regardless of the condition.
  • The condition is evaluated at the end of each iteration.

  • do: Starts the loop and the code block that needs to be repeated.
  • condition: This is a boolean expression that is evaluated after each iteration. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop stops.
  • The code block inside the do part will always execute at least once, even if the condition is false initially.

Example

Output

  • Initially, the value of i is 1.
  • The statement inside the do block prints the value of i, and then i is incremented by 1.
  • After the block is executed, the condition i <= 5 is checked. Since i is 6 after the fifth iteration, the loop stops.

A do-while loop is particularly useful when you need to ensure that the code inside the loop is executed at least once, regardless of the condition. For example, when validating user input or when a specific action must be performed at least once before checking a condition.

In contrast, a while loop checks the condition before the code block is executed, so if the condition is initially false, the code may never run.