Java do while example
There are four ways of looping with Java:for loops,for-each loops (since Java 1.5),while loops and thedo-while loops.
In this example, I will show how to use thedo-while loops to repeat blocks of statements in Java.
do-while structure
Ado-while has the following base structure:
do {// the code block to repeat} while(boolean_expr);As you can see, the boolean expressionboolean_expr is evaluated in the end of thedo-while block. This means that, whetherboolean_expr istrue orfalse, thedo-while block will execute at least one time.
Let’s see an example:
SimpleDoWhileExample
Create a class calledSimpleDoWhileExample with the following code:
package com.javacodegeeks.example;public class SimpleDoWhileExample {public static void main(String[] args) {boolean f = false;int count = 1;do {System.out.printf("This gets printed %d times\n",count);count++;} while (f);}}Since thef value is checked at the bottom of thedo-while block, this will print this:
This gets printed 1 times
Normally, you would want to use thedo-while loop when you want to ask something and the answer of the question determines whether the loop will go on executing or not. For more, check the following example.
DoAddWhileNotZero
In this example, we will show how to find the sum of some numbers, until the user enters 0 (which means that we should stop the loop). Create a class calledDoAddWhileNotZero with this source code:
package com.javacodegeeks.example;public class DoAddWhileNotZero {public static void main(String[] args) {java.util.Scanner stdIn = new java.util.Scanner(System.in);int sum = 0;int num;do {System.out.print("Enter a number (0 to stop): ");num = stdIn.nextInt();sum += num;} while(num != 0);System.out.println("The sum of all numbers is "+sum);}}So, we get the number from the user by using ajava.util.Scanner instance, and after adding this number to the variablesum (adding 0 won’t make a difference), we check if the number entered is 0. If not, the loop is executed once again.
One sample output of this example is:
Enter a number (0 to stop): 7Enter a number (0 to stop): 2Enter a number (0 to stop): 0The sum of all numbers is 9
Download Code
You can download the full source code of this example here :DoWhileExample

Thank you!
We will contact you soon.



