do-while loop in Java With Examples

A do-while loop in Java repeatedly executes a block of statement while the given condition is true. Java do-while loop is similar to while loop except one difference that the condition in the do-while loop is evaluated at the bottom rather than at the top (as is the case with while loop). Since the condition in do while loop is evaluated after the loop body, the statements within the do while block are always executed at least once.

Syntax of the do-while loop in Java is as follows-

Block of code that is executed with in a loop is enclosed with in curly braces.

Java do while loop execution flow

Following image shows the execution flow of the do while loop. do while loop in Java

In each iteration of the do-while loop body of the loop is executed first and then the condition is evaluated. Condition must be a boolean expression, if the expression evaluates to true then the loop is repeated, if expression evaluates to false then the loop terminates.

Java do while loop examples

1- First example uses do while loop to print numbers from 1 to 10.

Output

2- Second example uses do while loop to print numbers in reverse order 10 to 1.

Output

3- do-while loop works very well where you want to iterate for user’s choice until specific choice is made. do-while loop makes sense here because you want user’s input at lease once.

Output

That’s all for the topic do-while loop in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

  • for Loop in Java With Examples
  • Static Keyword in Java
  • Difference Between CountDownLatch And CyclicBarrier in Java
  • Life Cycle of a Thread (Thread States) in Java
  • Matrix Multiplication Java Program
  • Word Count Program Using MapReduce in Hadoop
  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.