Do While Loop in Java: Syntax, Examples, and Practical Applications
By Rohit Sharma
Updated on May 26, 2025 | 15 min read | 14K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on May 26, 2025 | 15 min read | 14K+ views
Share:
Table of Contents
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!
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);
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:
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:
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:
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.
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.
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:
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.
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.
⚠️ Warning:
Make sure your validation condition eventually becomes true to prevent the program from prompting indefinitely, which could cause the application to hang.
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:
⚠️ 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.
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:
⚠️ Warning:
Limit the number of password attempts to avoid infinite input loops and potential security risks. Always implement a maximum attempt counter.
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:
⚠️ Warning:
Allow users a clear way to exit the refresh loop to prevent the application from getting stuck in continuous refresh mode.
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.
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:
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:
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 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:
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.
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. |
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:
Examples:
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.
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.
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.
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:
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:
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.
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:
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?
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:
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:
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.
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
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
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
Top Resources