Java do-while Loop

Home / Core Java / Java do-while Loop

Java do-while Loop


Java do-While Loop :

The do-while loop in Java is similar to the while loop, with one crucial difference: the do-while loop executes its block of code at least once, regardless of the condition. After the first execution, it checks the condition, and if it's true, the loop continues to execute. If the condition is false, the loop stops.

Syntax:

The syntax for the do-while loop in Java is as follows:


  • The block of code within the curly braces {} will execute at least once before checking the condition.
  • condition: It's a boolean expression that determines whether the loop should continue. If this condition is true, the loop will continue to execute. If the condition is false, the loop will terminate.

Example:

Let's take an example to understand the do-while loop:


In this example:

  • count is initialized to 1.
  • The do-while loop block executes first, printing "Count is: 1".
  • count is incremented to 2.
  • The condition count <= 5 is checked; since it's true, the loop continues.
  • The loop continues executing the block of code until count reaches 6 (when count <= 5 becomes false), and then it terminates.


Key Points:
  • Execution before condition check: Unlike the while loop, the do-while loop guarantees that the block of code executes at least once before the condition is checked.
  • Checking condition: After the first execution, the loop checks the condition. If true, the loop continues. If false, the loop ends.
  • Updating variables: Like the while loop, ensure to update the variables within the loop to potentially alter the condition and avoid an infinite loop.

The do-while loop is beneficial when you want to execute a block of code at least once, regardless of the condition.