while loop

Java do while example

There are four ways of looping with Java: for loops, for-each loops (since Java 1.5), while loops and the do-while loops.

In this example, I will show how to use the do-while loops to repeat blocks of statements in Java.
 
 
 
 
 
 

do-while structure

A do-while has the following base structure:

do {
// the code block to repeat
} while(boolean_expr);

As you can see, the boolean expression boolean_expr is evaluated in the end of the do-while block. This means that, whether boolean_expr is true or false, the do-while block will execute at least one time.

Let’s see an example:

SimpleDoWhileExample

Create a class called SimpleDoWhileExample 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 the f value is checked at the bottom of the do-while block, this will print this:

This gets printed 1 times

Normally, you would want to use the do-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 called DoAddWhileNotZero 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 a java.util.Scanner instance, and after adding this number to the variable sum (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): 7
Enter a number (0 to stop): 2
Enter a number (0 to stop): 0
The sum of all numbers is 9

Download Code

Download
You can download the full source code of this example here : DoWhileExample

Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button