The Wayback Machine - http://web.archive.org/web/20240914155001/https://www.geeksforgeeks.org/java-do-while-loop-with-examples/
Open In App

Java do-while loop with Examples

Last Updated : 22 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body.

Syntax: 

do
{
    // Loop Body
    Update_expression
}

// Condition check
while (test_expression);

Note: The test_expression for the do-while loop must return a boolean value , else we would get compile-time error.

Application of do-while : Its example application is showing some kind of menu to the users. 

For example: 

You are implementing a game where you show some options to the user, press 1 to do this .., press 2 to do this .. etc and press ‘Q’ to quit the game. So here you want to show the game menu to the user at least once, so you write the code for the game menu inside the do-while loop.

Image

Illustration:

Java




// Java Program to Illustrate One Time Iteration
// Inside do-while Loop
// When Condition IS Not Satisfied
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // initial counter variable
        int i = 0;
 
        do {
 
            // Body of loop that will execute minimum
            // 1 time for sure no matter what
            System.out.println("Print statement");
            i++;
        }
 
        // Checking condition
        // Note: It is being checked after
        // minimum 1 iteration
        while (i < 0);
    }
}


Output

Print statement

Output explanation:

In the above code, we figured out that the condition is checked later as the body inside do will get executed one time without fail as the condition is checked later onwards. Hence whenever we want to display the menu and later on proceed command on the terminal, we always use do-while loop.

Components of do-while Loop  

A. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. For example: 

i <= 10

B. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. For example:  

i++;

Execution of do-While loop 

  1. Control falls into the do-while loop.
  2. The statements inside the body of the loop get executed.
  3. Updation takes place.
  4. The flow jumps to Condition
  5. Condition is tested. 
    1. If Condition yields true, go to Step 6.
    2. If Condition yields false, the flow goes outside the loop
  6. The flow goes back to Step 2.

Flowchart do-while loop:

Image

Implementation:

Example 1: This program will try to print “Hello World” 5 times.  

Java




// Java Program to Illustrate Do-while Loop
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Declaring and initialization expression
        int i = 1;
 
        // Do-while loop
        do {
 
            // Body of do-while loop
            // Print statement
            System.out.println("Hello World");
 
            // Update expression
            i++;
        }
 
        // Test expression
        while (i < 6);
    }
}


Output: 

Hello World
Hello World
Hello World
Hello World
Hello World

 

Auxiliary Space: O(1)

Output explanation: 

The program will execute in the following manner as follows:

  1. Program starts.
  2. i is initialized with value 1.
  3. Execution enters the loop
    • “Hello World” gets printed 1st time.
    • Updation is done. Now i = 2.
  4. Condition is checked. 2 < 6 yields true.
  5. Execution enters the loop.
    • “Hello World” gets printed 2nd time.
    • Updation is done. Now i = 3.
  6. Condition is checked. 3 < 6 yields true.
  7. Execution enters the loop
    • “Hello World” gets printed 3rd time
    • Updation is done. Now i = 4.
  8. Condition is checked. 4 < 6 yields true.
  9. Execution enters the loop
    • “Hello World” gets printed 4th time
    • Updation is done. Now i = 5.
  10. Condition is checked. 5 < 6 yields true.
  11. Execution enters the loop
    • “Hello World” gets printed 5th time
    • Updation is done. Now i = 6.
  12. Condition is checked. 6 < 6 yields false.
  13. The flow goes outside the loop.

Example 2

Java




// Java Program to Illustrate Do-while Loop
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Declaring and initializing integer values
        int x = 21, sum = 0;
 
        // Do-while loop
        do {
 
            // Execution statements(Body of loop)
 
            // Here, the line will be printed even
            // if the condition is false
            sum += x;
            x--;
        }
 
        // Now checking condition
        while (x > 10);
 
        // Summing up
        System.out.println("Summation: " + sum);
    }
}


Output: 

Summation: 176

 

Example 3: do-while loop without curly braces {}

Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
      int i=1;
      do
        // only single statement in do block
        System.out.println("Hello GFG!");
      // this condition is false so only do block will execute
      while(i>=3);
       
       
    }
}


Output

Hello GFG!

&list=PLqM7alHXFySF5ErEHA1BXgibGg7uqmA4_&ab_channel=GeeksforGeeks

Related Articles: 

  1. Loops in Java
  2. Java For loop with Examples
  3. Java while loop with Examples
  4. Difference between while and do-while loop in C, C++, Java
  5. Difference between for and do-while loop in C, C++, Java


Previous Article
Next Article

Similar Reads

Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; int main() { int i =
2 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number o
4 min read
Difference between for and do-while loop in C, C++, Java
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization condition; testing condition; increment/decrement) { statement(s) } Flow
2 min read
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let's understand the basic differences between a for loop and a while loop. for Loop A for loop provides a concise way of writing the loop structure.
5 min read
C++ While Loop
While Loop in C++ is used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test condition. Loops in C++ come into use when we need to repeatedly execute a block of statements. During the study of the 'for' loop in C++, we have seen that the number of itera
3 min read
C++ Do/While Loop
Loops come into use when we need to repeatedly execute a block of statements. Like while the do-while loop execution is also terminated on the basis of a test condition. The main difference between a do-while loop and a while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled where
3 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i &lt;=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read
How to Avoid TLE While Coding in Java?
Avoiding Time Limit Exceeded(TLE) is one of the most important aspects that we need to take care of while doing competitive coding as well as while answering questions on DSA during a technical PI. In this context, one commonly asked question across all coding platforms is sorting or problems that involve sorting. The following code is something I
5 min read
ConcurrentModificationException while using Iterator in Java
ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException. Here we will be underst
3 min read
Java - Parameters Responsible for Difference in Outputs while Running on Local IDE vs Online IDE
The concept involved in the difference in output between running a Java program on a local IDE and an online IDE is the environment in which the program is being run. The specific version of Java, the settings and configurations of the IDE, and the instructions in the program can all affect the output of the program. To understand the differences i
4 min read
Remove an Entry using key from HashMap while Iterating over it
Given a HashMap and a key in Java, the task is to remove an entry from this HashMap using the key, while iterating over it. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: {1=Geeks, 3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 3 Output: {1=G, 2=e, 4=k, 5=s} Using Java 7 and before: Get the Hash
3 min read
Remove an Entry using value from HashMap while Iterating over it
Given a HashMap and a value in Java, the task is to remove an entry from this HashMap using the value, while iterating over it. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, value = "ForGeeks" Output: {1=Geeks, 3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, value = k Output: {1=G, 2=e, 3=e, 5=s} Using Java 7 and bef
3 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
What Factors one should Keep in Mind while doing E-Commerce?
Purchase or selling things, products, services, or goods over the internet is known as E-Commerce. Or in other words, running a business using an electronic medium is known as E-commerce. Using E-commerce, people can view(browse) the products, buy or sell them, i.e., a type of store that works online. People can add the final products to buy on a c
5 min read
How to PopUp DatePicker While Clicking on EditText in Android?
In android applications date pickers are used to pick the date from the calendars and display them within our text view. Many times we have to display this date picker dialog box by clicking on edit text and then we have to display that date within our edit text. In this article, we will take a look at How to Pop Up a Date Picker Dialog in the andr
4 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections. This loop also makes the code more readable and r
1 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
For-each loop in Java
Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by
4 min read
For Loop in Java | Important points
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three type
6 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i &lt;= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Practice Tags :