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, statements within the do while block are always executed at least once.
Syntax of the do-while loop in Java is as follows-
do { //body } while (expression);
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.
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.
public class DoWhileDemo { public static void main(String[] args) { int i = 1; do { System.out.println("Value- " + i); i++; } while (i <= 10); } }Output
Value- 1 Value- 2 Value- 3 Value- 4 Value- 5 Value- 6 Value- 7 Value- 8 Value- 9 Value- 10
2- Second example uses do while loop to print numbers in reverse order 10 to 1.
public class DoWhileDemo { public static void main(String[] args) { int i = 10; do { System.out.println("Value- " + i); i--; } while (i > 0); } }Output
Value- 10 Value- 9 Value- 8 Value- 7 Value- 6 Value- 5 Value- 4 Value- 3 Value- 2 Value- 1
3- do-while loop works very well where you want to iterate for user’s choice until specific choice is made. Using do-while loop makes sense here because you want user’s input at lease once.
public class DoWhileDemo { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int i; do { System.out.print("Enter a number (0 to exit): "); i = sc.nextInt(); System.out.print("Entered number: " + i); System.out.println(); } while (i > 0); System.out.println("Out of loop"); } }Output
Enter a number (0 to exit): 3 Entered number: 3 Enter a number (0 to exit): 20 Entered number: 20 Enter a number (0 to exit): 6 Entered number: 6 Enter a number (0 to exit): 0 Entered number: 0 Out of loop
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
- Java Continue Statement With Examples
- CountDownLatch Vs CyclicBarrier in Java
- Java Executor Tutorial - Executor, ExecutorService, ScheduledExecutorService
- Matrix Subtraction Java Program
- How to Convert String to int in Java
- Hadoop MapReduce Word Count Program
- Spring Autowiring Example Using XML Configuration
No comments:
Post a Comment