Java do while Loop

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Do While loop in Java is also called an exit-control loop will always execute the blockJavacode once before checking the condition at the end of the loop. This differs from the while loop, which checks the condition before executing the loop's body.

Syntax

The syntax of a do-while loop in Java is as follows:

Different Components of do-while Loop

  • Java: This keyword is Java, the block of the loop.
  • Statements to execute: This block of code will run at least once before the condition is tested.
  • While: while is used to specify the condition that will be evaluated to determine if the loop will execute again.
  • Condition: This is the boolean expression that is checked after the execution of the loop's body. If true, the loop will continue; if false, the loop ends.

Execution of do-While Loop

The do-while loop in Java starts with the execution of the loop's body. After the body is executed, the condition is checked. After checking the condition, the loop will execute again if the condition becomes true. But if the condition is false, then the loop will terminate, and the control passes to the other statement following the do-while loop.

Flowchart of do-while Loop

flowchart-of-do-while-in-java

Example

Here's a simple example of a do-while loop in Java that prints numbers from 1 to 5:

Java Infinitive do-while Loop

An infinitive do-Javae loop continues forever unless an external intervention (such as a break statement) occurs. This happens when the condition always remains true. For example:

What is the Main Difference between a while and a do-while in Java?

do whilewhile
The loop will execute at least once.The loop does not guarantee that it will be executed at least once.
The conditional statement comes at the end of the do-while block.The conditional statement comes at the top of the while block.
The general form of do while loop is: do{ code } while( condition );The general form of while loop is: while( condition ) { code }

Conclusion

  • The do while loop in Java is guaranteed always to execute at least once.
  • The conditional statement is given at the end of the do-while block.
  • We can also calledJavawhile loop a post-tested loop. The condition is checked after updating loop variables.

Learn More

Do you still want to learn more about loops in Java? You can visit Scaler Topics for more information. Check out this article on loops in Java for detailed information on all types of loops in Java. Also, you can visit For each loop in Java