Java Do While Loop

In this tutorial you will learn about the Java Do While Loop and its application with practical example.

Java Do While Loop

The do-while loop executes a block of statements inside the loop body first and then tests the condition for the next iteration and executes next only if the condition is true. The do…while loop is much similar to Java while loop with one major difference, in the do…while loop block of statements inside the loop body executes at least once.

Java Do-While Loop Flow Diagram

swift-repeat-while-loop-flowchart-diagram

Syntax:-

Here, the loop executes a block of statements inside the loop body first and then tests the condition provided along with the while keyword for the next iteration and executes next only if the condition is true. Condition is a Boolean expression that results in either True or False, if it results in True then statements inside the loop body are executed and the condition is evaluated again. This process is repeated until the condition is evaluated as False. If the condition results in False then the loop is terminated and control is transferred to the next statement.

Example:-

Here, we have initialized ctr and maxCtr to 1 and 5 respectively, in the next statement we have loop body inside the pair of curly brackets {} after do keyword, statements inside loop body are executed first then control is passed to the condition ctr <= maxCtr provided along with while keyword for next iteration. If the test condition returns True, then control is passed again to loop body for the next iteration. If the condition results in False then the loop is terminated and control is transferred to the next statement. Inside the loop body, we have incremented the ctr value by one for each iteration. When we run the above java program, we see the following output –

Output:-

java_do_while_loop_example

In this tutorial we have learn about the Java Do While Loop and its application with practical example. I hope you will like this tutorial.