View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Do While Loop in Java: Syntax, Examples, and Practical Applications

By Rohit Sharma

Updated on May 26, 2025 | 15 min read | 14K+ views

Share:

Did You Know? Over 90% of Fortune 500 companies still use Java for their software development needs in 2025, highlighting its enduring role in enterprise environments.

Do while loop Java is a key control structure that ensures your code runs at least once before checking a condition. This makes it ideal for tasks like input validation and menu-driven applications where you need guaranteed initial execution. Its unique ability to execute code before evaluating the condition helps you write more reliable and predictable programs.

This blog will show how the do while loop Java work, explain its syntax in detail, and provide practical examples. You’ll discover when and how to use it effectively in your Java projects to improve code clarity and functionality.

Enhance your Java and other programming skills with upGrad’s online Software Engineering courses. Learn practical techniques and build your expertise to advance your career!

Components of a Do-While Loop Java

Let’s break down the do while syntax Java and components of the Java do while loop to give you a comprehensive understanding of its structure and functionality. 

A do while loop in Java is structured like this: 

do {
    // block of code
} while (condition);

 

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Component

Description

Syntax Example

Code Example

do keyword Starts the loop and marks the beginning of the code block that executes at least once. do { do {
Code Block Contains the statements to be executed during each iteration of the loop. { ... } { System.out.println(i); i++; }
while keyword Introduces the loop’s condition, checked after each execution of the code block. } while (condition); } while (i < 5);
Condition A boolean expression evaluated after each iteration to determine whether the loop continues. (i < 5) (i < 5)
Semicolon (;) Marks the end of the entire do-while loop statement after the condition. ); } while (i < 5);

Now let’s move on to how the Java do while loop actually executes and when it’s most useful. 

In 2025, professionals skilled in programming and AI technologies continue to be highly sought after to drive innovation and efficiency in businesses. If you want to strengthen your expertise in these areas with a focus on Java and programming, consider these top courses:

How Does a Do-While Loop Execute?

In this section, you'll go through the detailed execution flow of a Java do-while loop to help you grasp its behavior and understand how it operates in different scenarios.

Here’s a Java while do while loop example: 

public class DoWhileExample {
    public static void main(String[] args) {
        int num = 1;  // Initialize the counter
        int max = 5;  // Set the upper limit

        // Do-While Loop starts
        do {
            System.out.println("Iteration " + num);  // Print the current iteration
            num++;  // Increment the counter
        } while (num <= max);  // Check the condition after each iteration
    }
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Step-by-Step Execution Flow:

  1. Initialization: The program starts with num = 1 and max = 5.
    • Comment: The variable num keeps track of the current iteration, while max sets the stopping condition for the loop.
  2. First Execution of the Do Block:
    • The do block runs first before checking the condition.
    • Output: "Iteration 1" is printed because the loop starts with num = 1.
    • Action: num is then incremented by 1, so num becomes 2.
  3. Condition Check: The program then checks if num <= max (2 <= 5), which is true.
    • The loop continues because the condition is true.
  4. Second Iteration: The do block is executed again with num = 2.
    • Output: "Iteration 2" is printed.
    • Action: num is incremented by 1 again, so num becomes 3.
  5. Subsequent Iterations: This process repeats for num = 3, num = 4, and num = 5. The output for each will be:
    • "Iteration 3", "Iteration 4", "Iteration 5".
    • The counter num keeps increasing by 1 until it reaches the value 6.
  6. Final Condition Check: Once num = 6, the condition 6 <= 5 is checked and is false.
    • Since the condition is false, the do while loop Java stops executing.

Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced

Output: 

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Explanation:

  • First Run: The first execution happens before checking the condition, ensuring at least one run.
  • Subsequent Runs: After each iteration, the condition num <= max is checked. If true, the loop continues. If false, the loop stops.
  • Loop End: The do while Java loop stops once num exceeds max (after printing "Iteration 5").

    ⚠️ Warning:

    Make sure the condition in your do-while loop eventually becomes false. Otherwise, the loop will run infinitely, causing your program to hang or crash.

Also Read: While loop in MATLAB: Everything You Need to Know

Now that you understand the execution flow of the Java do-while loop, let’s explore its practical applications and see how it’s used in different scenarios.

Practical Applications of Do-While Loop Java

The do while loop Java is especially effective when you need the code block to run at least once before evaluating any condition. This makes it well-suited for situations like processing user input or performing repeated actions until a desired condition is met. 

Exploring its practical applications shows how this control structure can help you write clearer and more reliable Java programs.

1. Menu-Driven Program

A do while loop example is perfect for creating a menu-driven program. Since you want the menu to display at least once, the Java while do while is the ideal choice here. 

import java.util.Scanner;

public class MenuDrivenProgram {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;

        do {
            System.out.println("Menu:");
            System.out.println("1. Option 1");
            System.out.println("2. Option 2");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            choice = sc.nextInt();

            switch (choice) {
                case 1:
                    System.out.println("You chose Option 1");
                    break;
                case 2:
                    System.out.println("You chose Option 2");
                    break;
                case 3:
                    System.out.println("Exiting...");
                    break;
                default:
                    System.out.println("Invalid option! Please try again.");
            }
            // The loop continues as long as the choice is NOT equal to 3 (Exit).
            // Logical condition: choice != 3
            // This means the menu will keep showing until the user selects option 3.
        } while (choice != 3); // Loop until user chooses 'Exit'

        sc.close();
    }
}

Output: 

Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 1
You chose Option 1
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 3
Exiting...

Explanation:

The do while Java loop ensures the menu is displayed to the user at least once before any condition is checked. This is important because you want the user to see the menu immediately when the program runs, without any initial checks or delays.

Inside the loop, the program prints the menu options and then prompts the user to enter their choice using a Scanner. Once the user inputs a number, the switch statement evaluates the choice:

  • If the user selects Option 1 or Option 2, the program acknowledges the choice by printing a corresponding message.
  • If the user inputs 3, the program prints "Exiting..." and then the loop condition (choice != 3) becomes false, causing the loop to terminate.
  • For any other input, the program informs the user that the option is invalid and asks them to try again.

    Because the do while syntax Java loop runs after the first menu display and input, even if the user enters an invalid option initially, the menu will continue to appear repeatedly. This guarantees continuous interaction until the user decides to exit.

    This structure is ideal for menu-driven programs because it provides a simple, clear way to keep presenting options and handling user inputs, all while ensuring the menu is never skipped or hidden during program execution.

    ⚠️ Warning:

    Ensure your exit condition is reachable (e.g., choosing option 3) to avoid infinite loops. Without a proper exit, the menu will keep displaying endlessly.

2. Input Validation

Another common application of the Java do while loop is for input validation. 

If you want to ensure that the user enters valid input, you can use the do-while loop to prompt the user until they provide the correct input repeatedly. 

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num;

        do {
            System.out.print("Enter a positive number: ");
            num = sc.nextInt();
            if (num <= 0) {
                System.out.println("Invalid input! Please try again.");
            }
            // The condition checks if the input is less than or equal to 0.
            // Logical condition: num <= 0
            // If true, the loop repeats, prompting the user again.
            // This ensures the loop continues until the user enters a positive number.
        } while (num <= 0); // Continue looping until valid input is entered

        System.out.println("You entered a valid number: " + num);
        sc.close();
    }

Output: 

Enter a positive number: -5
Invalid input! Please try again.
Enter a positive number: 10
You entered a valid number: 10

Explanation:

The do while loop Java guarantees that the program asks the user to enter a number at least once before checking its validity. This is crucial because you want to prompt the user immediately, regardless of any prior input.

  • The do-while loop example here ensures that the program keeps prompting the user until a valid number is entered.
  • The loop will execute at least once, even if the user initially enters an invalid input.
  • This is a practical way to validate input without repeating the code multiple times.

⚠️ Warning:

Make sure your validation condition eventually becomes true to prevent the program from prompting indefinitely, which could cause the application to hang.

3. Sum of Natural Numbers

The Java do while loop is also useful for simple calculations, such as calculating the sum of natural numbers up to a given number. 

The loop will continue summing the numbers until the specified limit is reached. 

public class SumOfNaturalNumbers {
    public static void main(String[] args) {
        int num = 5;  // Example input
        int sum = 0;
        int i = 1;

        do {
            sum += i;  // Add the current number to sum
            i++;       // Increment the counter
            // The condition below checks if the counter i is less than or equal to num.
            // Logical condition: i <= num
            // As long as this is true, the loop continues to add numbers to sum.
        } while (i <= num); // Loop until the counter exceeds 'num'

        System.out.println("Sum of natural numbers up to " + num + " is: " + sum);
    }
}

Output: 

Sum of natural numbers up to 5 is: 15

Explanation:

  • The do-while loop ensures that the sum calculation starts at least once, beginning with i = 1.
  • Inside the loop, the current value of i is added to the running total sum.
  • After each addition, i is incremented by 1 to move to the next number.
  • The loop continues executing as long as i is less than or equal to the specified limit num.
  • This example shows that do while syntax Java loops are well-suited for tasks requiring cumulative calculations that must run at least once.

⚠️ Warning:

Confirm that your loop’s counter and condition are set correctly to avoid infinite looping or skipping the loop entirely if the initial condition is false.

Also Read: For-Each Loop in Java [With Coding Examples]

Next, look at how you can use the loop for array iteration and complex tasks, including nested loops.

4. Password Authentication

In security systems, prompting for a password until the correct one is entered or the maximum attempts are reached is a common use case. The do while loop Java ensures the prompt appears at least once and repeats as necessary.

import java.util.Scanner;

public class PasswordAuthentication {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String correctPassword = "pass123";
        String inputPassword;
        int attempts = 0;

        do {
            System.out.print("Enter password: ");
            inputPassword = sc.nextLine();
            attempts++;
            if (!inputPassword.equals(correctPassword)) {
                System.out.println("Incorrect password, try again.");
            }
        } while (!inputPassword.equals(correctPassword) && attempts < 3);

        if (inputPassword.equals(correctPassword)) {
            System.out.println("Access granted.");
        } else {
            System.out.println("Too many attempts. Access denied.");
        }

        sc.close();
    }
}

Output:

Enter password: wrongpass  
Incorrect password, try again.  
Enter password: pass123  
Access granted.  

Explanation:

  • The do while loop Java prompts the user for a password at least once before checking its validity.
  • If the entered password is incorrect, the loop repeats until the correct password is entered or the attempt limit (3) is reached.
  • This approach improves security by limiting attempts while ensuring the user always sees the prompt initially.
  • It balances usability and protection by allowing multiple tries without skipping the first input request.

⚠️ Warning:

Limit the number of password attempts to avoid infinite input loops and potential security risks. Always implement a maximum attempt counter.

5. Dashboard Data Refresh

In monitoring applications, the do-while loop is useful to display data at least once and then refresh repeatedly based on user input.

import java.util.Scanner;

public class DashboardRefresh {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char refresh;

        do {
            System.out.println("Dashboard data: CPU 55%, Memory 70%");
            System.out.print("Refresh dashboard? (y/n): ");
            refresh = sc.nextLine().charAt(0);
        } while (refresh == 'y' || refresh == 'Y');

        System.out.println("Exiting dashboard...");
        sc.close();
    }
}

Output:

Dashboard data: CPU 55%, Memory 70%  
Refresh dashboard? (y/n): y  
Dashboard data: CPU 55%, Memory 70%  
Refresh dashboard? (y/n): n  
Exiting dashboard...  

Explanation:

  • The dashboard data is displayed once immediately when the program starts.
  • The user is prompted to refresh the dashboard data or exit.
  • The do while loop Java continues running as long as the user inputs ‘y’ or ‘Y’, allowing repeated updates.
  • This setup provides real-time updates without restarting the application, enhancing user experience.

⚠️ Warning:

Allow users a clear way to exit the refresh loop to prevent the application from getting stuck in continuous refresh mode.

Other Practical Applications of Do While Loop Java

Beyond the common uses, the do-while loop is also valuable in several other programming scenarios. These applications use its ability to execute code at least once and repeat based on conditions, making it ideal for complex and interactive tasks. 

Here are some additional practical uses with examples and explanations:

Application

Description

Example

Game Loops Manage game cycles where at least one round must play before checking if the player wants to quit. Running a turn-based game that processes player input and updates game state until the player exits.
Multi-dimensional Array Traversal Use nested do-while loops to traverse rows and columns of 2D or 3D arrays. Printing elements of a 2D matrix row by row and column by column using nested do-while loops.
Retry Operations Automatically retry operations like network calls or file I/O until successful or max attempts hit. Repeatedly attempt to download a file, retrying if network errors occur, stopping after 5 tries.
Wizard-style Interfaces Guide users through multi-step processes, ensuring each step executes at least once. Step-by-step form submission where each page asks for user input and validates before moving on.
Sensor Polling Continuously monitor device or sensor status, repeating checks until a specific condition is met. Polling a temperature sensor every few seconds until the temperature reaches a threshold.

These applications highlight the do-while loop’s flexibility in handling interactive, repetitive, and condition-dependent programming tasks. 

Also Read: For-Each Loop in Java [With Coding Examples]

Next, let’s look at how you can use the loop for array iteration and complex tasks, including nested loops.

Iteration and Nesting with Do-While Loop 

The Java do-while loop is well-suited for iterating through arrays and can be nested to handle more complex operations, such as working with multi-dimensional arrays and matrices. 

Using nested do-while loops allows you to manage intricate data structures effectively, giving you greater control over the iteration process. Exploring these techniques will help you apply the do-while loop in a variety of programming scenarios with precision and flexibility.

Let’s get into the different techniques one by one: 

Iterating Through Arrays with Do While Loop Java

The do while loop Java is useful for iterating through arrays because it guarantees the loop body runs at least once. This is helpful when you want to process elements starting from the first index without pre-checking conditions. 

It ensures that even if the array has one element or certain conditions are initially false, the iteration still occurs correctly, making it a reliable choice for simple array traversal.

Here’s an example of iterating through an array using a do-while loop in Java: 

public class ArrayIteration {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};  // Array to iterate over
        int index = 0;  // Start at the first index
        
        do {
            System.out.println("Element at index " + index + ": " + arr[index]);
            index++;  // Move to the next index
        } while (index < arr.length);  // Continue until all elements are processed
    }
}

Output: 

Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

Explanation:

  • The do-while loop begins by accessing and printing the first element of the array at index 0, ensuring the operation runs at least once.
  • After printing each element, the index variable is incremented to move to the next position in the array.
  • Following each iteration, the loop checks the condition index < arr.length to determine if there are more elements to process.
  • The loop continues running as long as the index is within the bounds of the array, ensuring no element is missed.
  • This method is effective for processing all elements in an array, making the do-while loop a reliable choice for array iteration tasks.

Start your Java journey with upGrad’s Core Java Basics course. Learn the fundamental concepts and syntax needed to write effective and reliable programs. This course will prepare you to build solid applications and lay the groundwork for further Java learning.

Nesting Do-While Loops

Nesting do-while loops involves placing one loop inside another, which is especially useful for working with multi-dimensional arrays or complex data structures. The outer loop typically manages rows or higher-level elements, while the inner loop handles columns or nested elements. 

This structure allows you to systematically access every element within multi-layered arrays or matrices, providing precise control over each dimension of iteration.

Here’s an example of nesting do-while loops to print the elements of a 2D array

public class NestedDoWhileLoop {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};  // 2D array (matrix)
        int i = 0;  // Row index
        
        do {
            int j = 0;  // Column index for each row
            do {
                System.out.print(matrix[i][j] + " ");  // Print current element
                j++;  // Move to the next column
            } while (j < matrix[i].length);  // Continue until all columns in the row are processed
            System.out.println();  // Move to the next line after each row
            i++;  // Move to the next row
        } while (i < matrix.length);  // Continue until all rows are processed
    }
}

Output: 

1 2 3 
4 5 6 
7 8 9 

Explanation:

  • Nesting: The outer do-while loop handles rows of the matrix, while the inner do-while loop processes each element within a row.
  • Condition checks: After each inner loop iteration, the column index (j) is incremented, and the condition checks if the column index is less than the row length.
  • Matrix printing: The matrix is printed row by row, with each row being processed by the inner loop.
  • At least one iteration: This method ensures that the matrix is printed completely, even if the number of rows or columns changes. 
  • The output displays the matrix elements row by row, with each number separated by a space.
  • Each line corresponds to a row in the 2D array, showing the values stored in that row sequentially.
  • The inner do-while loop prints all elements in a single row before moving to the next line.
  • The outer do-while loop controls the progression through each row of the matrix until all rows are printed.
  • This output confirms that the nested do-while loops successfully iterate through every element of the 2D array, maintaining the matrix’s original structure.

With this understanding of array iteration and nested loops, let's now move forward to explore how the Java do while loop compares with the while loop, and when it’s best to use each one.

Do-While vs While Loop

The Java do while loop and the while loop are both used for repeating a block of code based on a condition, but they differ in how they evaluate the condition and when they execute the loop. 

Let’s break down the key differences to help you decide when to use each.

Aspect

Java Do-While Loop

Java While Loop

Condition Check The condition is checked after executing the code block. This means the loop always runs at least once before any condition evaluation. The condition is checked before executing the code block. If the condition is false initially, the loop may not run at all.
Guarantee of Execution Guaranteed to execute the code block at least once, regardless of the initial condition. No guarantee of execution; if the condition is false at the start, the code block will never execute.
Use Case Best used when you want to perform an action at least once and then repeat it based on a condition. Common in input validation, menu-driven programs, or any scenario where user interaction is needed first. Ideal when the loop should only run if a condition is true from the start. Suitable for scenarios like iterating over collections where pre-check is necessary.
Syntax java<br>do {<br> // code to execute<br>} while (condition);<br> java<br>while (condition) {<br> // code to execute<br>}<br>
Example java<br>int i = 0;<br>do {<br> System.out.println(i);<br> i++;<br>} while (i < 3);<br> java<br>int i = 0;<br>while (i < 3) {<br> System.out.println(i);<br> i++;<br>}<br>
Example Explanation Prints numbers 0 to 2, executing the loop body first before checking the condition, ensuring it runs once even if the initial condition is false (e.g., if i was initialized at 5). Prints numbers 0 to 2 only if the condition i < 3 is true before entering the loop. If i starts at 5, the loop body won't execute.

Why Use Java While Condition?

The Java do-while loop offers distinct benefits, especially when you need to make sure that the code block executes at least once before checking the condition.

Let’s go through some of the benefits: 

  • Guarantees at least one iteration: Unlike the while loop, which may skip the loop entirely if the condition is false, the do-while loop always runs the code block once.
  • Ideal for menu-driven programs: When you need to display a menu and accept user input repeatedly, you can ensure that the menu is displayed at least once, regardless of the user’s choice.
  • Input validation: In scenarios where you need to prompt the user for valid input, you can validate the input after performing the task, making sure it runs at least once.

Examples:

  • Password Authentication: Secure systems require users to enter a password to gain access. A do-while loop prompts for the password once and then validates it. If incorrect, the loop repeats until the correct password is entered or a maximum number of attempts is reached. This ensures the prompt always appears initially and adapts to user input, enhancing both security and usability.

Code:

import java.util.Scanner;

public class PasswordCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String correctPassword = "secure123";
        String inputPassword;
        int attempts = 0;

        do {
            System.out.print("Enter password: ");
            inputPassword = sc.nextLine();
            attempts++;
            if (!inputPassword.equals(correctPassword)) {
                System.out.println("Incorrect password. Try again.");
            }
        } while (!inputPassword.equals(correctPassword) && attempts < 3);

        if (inputPassword.equals(correctPassword)) {
            System.out.println("Access granted.");
        } else {
            System.out.println("Too many failed attempts. Access denied.");
        }
        sc.close();
    }
}

Output Example:

Enter password: pass123
Incorrect password. Try again.
Enter password: mypass
Incorrect password. Try again.
Enter password: secure123
Access granted.

Explanation:
The password prompt appears at least once and repeats until the user enters the correct password or exceeds the maximum of three attempts, enhancing both security and usability.

  • Dashboard Refresh in Monitoring Systems: Monitoring tools continuously update server or network data. A do-while loop refreshes the dashboard at least once to show current metrics, then checks if the user wants to refresh again or exit. This guarantees immediate data display at startup and allows seamless repeated updates without restarting.

Code:

import java.util.Scanner;

public class Dashboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char refresh;

        do {
            System.out.println("Dashboard data: CPU Usage 45%, Memory Usage 68%");
            System.out.print("Refresh dashboard? (y/n): ");
            refresh = sc.nextLine().charAt(0);
        } while (refresh == 'y' || refresh == 'Y');

        System.out.println("Exiting dashboard...");
        sc.close();
    }
}

Output Example:

Dashboard data: CPU Usage 45%, Memory Usage 68%
Refresh dashboard? (y/n): y
Dashboard data: CPU Usage 45%, Memory Usage 68%
Refresh dashboard? (y/n): y
Dashboard data: CPU Usage 45%, Memory Usage 68%
Refresh dashboard? (y/n): n
Exiting dashboard...

Explanation:
The dashboard data is shown once initially, then refreshes repeatedly as long as the user chooses ‘y’. This simulates a live data refresh without restarting the program.

  • Game Loops in Simple Games: Many games run core gameplay inside a loop until the player quits. A do-while loop ensures at least one full round or level is played before checking if the player wants to continue. This setup initializes game states, handles input, and updates graphics smoothly, preventing any part of the game cycle from being skipped.

Code:

import java.util.Scanner;

public class GameLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char playAgain;

        do {
            System.out.println("Playing the game...");
            // Game logic here
            System.out.print("Play again? (y/n): ");
            playAgain = sc.nextLine().charAt(0);
        } while (playAgain == 'y' || playAgain == 'Y');

        System.out.println("Thanks for playing!");
        sc.close();
    }
}

Output Example:

Playing the game...
Play again? (y/n): y
Playing the game...
Play again? (y/n): y
Playing the game...
Play again? (y/n): n
Thanks for playing!

Explanation:
The game executes at least one round, then asks if the player wants to continue. The loop repeats until the player chooses to stop, effectively managing gameplay flow.

Also Read: Control Statements in Java: What Do You Need to Know in 2024

Now, let's explore how you can enhance the flow of your loop with the break and continue statements in the do-while loop. 

Also Read: Control Statements in Java: What Do You Need to Know in 2024

Now, let's explore how you can enhance the flow of your loop with the break and continue statements in the do-while loop. 

Break and Continue in Do While Java Loop

The break and continue statements can be used in a Java do while loop to control the flow of execution more efficiently. These statements allow you to exit the loop or skip an iteration based on specific conditions.

Let’s look at how these work: 

Using the Break Statement

The break statement is used to exit the loop completely, regardless of whether the loop’s condition has been met. This is useful when you want to stop the loop based on a specific condition, even if the loop would otherwise continue.

Let’s look at a do while loop example using break: 

public class BreakExample {
    public static void main(String[] args) {
        int num = 0;

        do {
            num++;
            if (num == 5) {
                System.out.println("Breaking the loop at num = " + num);
                break;  // Exit the loop when num reaches 5
            }
            System.out.println("Current number: " + num);
        } while (num < 10);  // Loop continues until num is less than 10
    }
}

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Breaking the loop at num = 5

Explanation:

  • The do-while loop starts by incrementing num from 0 and executes the loop body at least once.
  • For each iteration, the current value of num is printed unless the break condition is met.
  • When num reaches 5, the if condition triggers the break statement.
  • The break statement immediately terminates the loop, preventing any further iterations—even though the loop condition (num < 10) would normally allow it to continue.
  • As a result, the program stops printing numbers after reaching 5, demonstrating how break can be used to exit loops early based on specific logic.
  • This approach is useful when you need to stop processing as soon as a certain condition is satisfied, improving efficiency and control flow in your program.

Improve your Java skills with upGrad’s Java Object-Oriented Programming course. Understand key principles like inheritance, encapsulation, and polymorphism to create clean, reusable, and well-organized code. These skills are essential for developing strong Java applications and advancing your programming career.

Using the Continue Statement

The continue statement allows you to skip the rest of the current iteration and proceed with the next iteration of the loop. This can be useful when you want to ignore certain iterations based on a condition, but still want the loop to continue running.

Here’s an example using continue: 

public class ContinueExample {
    public static void main(String[] args) {
        int num = 0;

        do {
            num++;
            if (num == 3) {
                System.out.println("Skipping num = " + num);
                continue;  // Skip the current iteration when num is 3
            }
            System.out.println("Current number: " + num);
        } while (num < 5);  // Loop runs until num is less than 5
    }
}

Output: 

Current number: 1
Current number: 2
Skipping num = 3
Current number: 4

Explanation:

  • The do-while loop increments num starting from 0 and executes the loop body at least once.
  • For each iteration, the loop checks if num equals 3.
  • When num is 3, the continue statement is triggered, which skips the remaining code in that iteration.
  • As a result, the message for num = 3 is not printed, and the loop proceeds directly to the next iteration.
  • For all other values of num, the current number is printed as expected.
  • This example demonstrates how continue allows you to bypass specific iterations based on conditions without terminating the entire loop, enabling more precise control over loop execution.

With a solid understanding of break and continue, you can now refine the flow of your Java do while loop. 

Next, let’s take a look at more advanced uses of the do-while loop, including handling multiple conditions and nesting loops for complex tasks.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Do While Java Loop with Multiple Conditions

The Java do while loop with multiple conditions, combining logical operators like AND (&&) and OR (||) allows you to control the loop's execution more precisely based on multiple criteria.

When you have more than one condition to check, you can use logical operators to combine these conditions inside the do-while loop example. This is useful when you need the loop to run based on more complex scenarios.

Here’s an example where we combine conditions using the AND operator (&&): 

public class MultipleConditionsExample {
    public static void main(String[] args) {
        int num = 1;  // Initial number
        int max = 10; // Max limit

        do {
            System.out.println("Current number: " + num);  // Print current number
            num++;  // Increment the number
        } while (num <= max && num % 2 == 0);  // Run until num is <= max and is even
    }
}

Output: 

Current number: 1

Explanation:

  • The do-while loop starts by printing the initial value of num, which is 1, before checking the conditions.
  • The loop’s continuation depends on two conditions combined with the AND operator (&&): num must be less than or equal to max and num must be even (num % 2 == 0).
  • Since the initial num value is 1, which is not even, the second condition fails right after the first iteration.
  • As a result, the loop stops immediately after printing “Current number: 1,” without repeating.
  • This example shows how combining multiple conditions with && controls loop execution strictly, requiring all conditions to be true for the loop to continue.

Now, let’s look at an example using the OR operator (||), which allows the loop to continue if either of the conditions is true. 

public class MultipleConditionsExample2 {
    public static void main(String[] args) {
        int num = 1;  // Initial number
        int max = 10; // Max limit

        do {
            System.out.println("Current number: " + num);  // Print current number
            num++;  // Increment the number
        } while (num <= max || num % 2 == 1);  // Run while num is <= max or is odd
    }
}

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
Current number: 6
Current number: 7
Current number: 8
Current number: 9
Current number: 10

Explanation:

  • The do-while loop begins by printing the initial value of num, which is 1, then increments num after each iteration.
  • The loop continues as long as either of the conditions is true: num is less than or equal to max or num is odd (num % 2 == 1).
  • Since num starts at 1 (which is odd), the loop continues regardless of the num <= max condition.
  • The loop keeps running, printing numbers from 1 to 10, because the first condition (num <= max) remains true throughout.
  • Once num exceeds 10, the loop checks the second condition; since the number is even, the second condition becomes false, causing the loop to end.
  • This example illustrates how using the OR operator (||) allows the loop to run if at least one condition is satisfied, making the loop less restrictive than using AND.

Now that the basics of do while syntax Java are sufficiently clear, let us have a look at how you can take your programming skills further with the help of expert guidance and courses by upGrad. 

How upGrad Advances Your Expertise in Programming?

Advancing your Java skills can open doors to exciting career opportunities in programming and software development. Whether you're a beginner or an experienced developer aiming to deepen your knowledge, upGrad offers a variety of specialized courses in machine learning, web development, and data structures to meet your goals.

At upGrad, you can select from hands-on programs that include expert mentorship and personalized feedback, helping you become job-ready and confident in handling complex projects.

Here are some top software related courses offered by upGrad:

Feeling unsure about where to begin with your programming career? Connect with upGrad’s expert counselors or visit your nearest upGrad offline centre to explore a learning plan tailored to your goals. Transform your programming journey today with upGrad!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference:

https://softjourn.com/insights/is-java-still-used

Frequently Asked Questions (FAQs)

1. When should I use a do-while loop instead of a while loop?

2. Can a do-while loop run infinitely? How to avoid that?

3. How do I break out of a do-while loop prematurely?

4. Can I nest do-while loops inside each other?

5. How do logical operators work with the condition in a do-while loop?

6. What happens if the condition in a do-while loop is initially false?

7. How to avoid common mistakes when using do-while loops?

8. How do I debug a do-while loop that runs unexpectedly?

9. Are do-while loops recommended for all looping scenarios?

10. How to use do-while loops in GUI applications?

Rohit Sharma

763 articles published

Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months