Learning About Do While Loop in Java

Learning About Do While Loop in Java

5 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 25, 2024 17:30 IST

Have you ever wondered how to repeatedly execute a block of code at least once and then based on some condition? In Java, the do-while loop provides this exact control flow, executing its body first and then checking the condition, making it perfect for scenarios where at least one iteration is required, no matter what. Let's understand more!

The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The primary characteristic of the do-while loop is that it guarantees the code inside the loop will execute at least once. This is because the condition is evaluated after the body of the loop has been executed.

You must explore Java Programming Courses to learn more!

Control Statements in Java - About and Types
Control Statements in Java - About and Types
Have you ever wondered how Java manages the flow of its programs so efficiently? The three types of control statements, namely decision-making statements, looping statements, and jump statements, allow Java...read more

Let's examine the workings of the do-while loop in Java, starting with syntax, a flowchart, and an explanation.

1. Syntax

do {
    // Statements to execute
} while (condition);

2. Flowchart

3. Explanation

  • Execute the code inside the do block first.
  • Check the while condition after executing the code.
  • If the condition is true, repeat from step 1,  if false, exit the loop.
  • Continue with the rest of the program.

Examples of Do-While Loop in Java

Let's see a few examples to understand the concept deeply!

Example 1: User Authentication

Problem Statement: A system prompts a user for a password until the correct password is entered.


 
import java.util.Scanner;
public class UserAuthentication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String correctPassword = "Java123";
String inputPassword;
do {
System.out.print("Enter password: ");
inputPassword = scanner.nextLine();
} while (!inputPassword.equals(correctPassword));
System.out.println("Access Granted!");
scanner.close();
}
}
Copy code

Output

Enter password: esha
Enter password: gupta
Enter password: Java123
Access Granted!

The code keeps prompting the user for a password until the correct one is entered. Once the user enters "Java123", the loop terminates, and "Access Granted!" is printed.

Example 2: Input Validation

Problem Statement: A program asks the user to enter a positive number and keeps asking until the user complies.


 
import java.util.Scanner;
public class PositiveNumberInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("Thank you for entering a positive number: " + number);
scanner.close();
}
}
Copy code

Output

Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 10
Thank you for entering a positive number: 10

The user is continually asked for a positive number. If the number is not positive, the loop repeats. When a positive number is entered, the message thanks the user and the loop ends.

Example 3: Menu Selection

Problem Statement: An application displays a menu to the user repeatedly until they choose to exit by entering '0'.


 
import java.util.Scanner;
public class MenuSelection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Play game");
System.out.println("2. Settings");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
// Assuming there are methods to playGame() and openSettings()
} while (choice != 0);
System.out.println("Thank you for using the application.");
scanner.close();
}
}
Copy code

Output

1. Play game
2. Settings
0. Exit
Enter your choice: 2
1. Play game
2. Settings
0. Exit
Enter your choice: 1
1. Play game
2. Settings
0. Exit
Enter your choice: 0
Thank you for using the application.

This code displays a menu to the user and asks them to make a choice. The loop continues until the user selects '0', which causes the application to print a thank you message and then close. If there were methods for playGame() and openSettings(), you could call them when options '1' or '2' are selected, respectively.

Key Takeaways

  • A do-while loop ensures the code inside the loop executes at least once before checking the loop's condition.
  • It's particularly useful when the initial condition depends on user input received within the loop.
  • Because the condition is evaluated after the loop's body, the loop may not execute again if the condition is not met on the first check.

Understanding If Condition in Java
Understanding If Condition in Java
Have you ever wondered how Java programs make decisions? The if condition in Java is the key. It allows code to branch out based on conditions, thus introducing dynamic decision-making...read more

Control Statements in Java - About and Types
Control Statements in Java - About and Types
Have you ever wondered how Java manages the flow of its programs so efficiently? The three types of control statements, namely decision-making statements, looping statements, and jump statements, allow Java...read more

If-Else Program in Java | About, Syntax, Flowchart and Examples
If-Else Program in Java | About, Syntax, Flowchart and Examples
Have you ever wondered how programs make decisions and adapt to different situations? The answer lies in the power of if-else statements. These statements allow us to control the flow...read more

Switch Case in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more

Mastering For Loops in Java: A Comprehensive Guide
Mastering For Loops in Java: A Comprehensive Guide
Learn how to use for loops in Java to control the flow of your programs and automate repetitive tasks. Understand the basics of for loops, nested for loops, for-each loops...read more

While Loop in Java | Java While Loop Example
While Loop in Java | Java While Loop Example
Learn to make your programs repeat actions over and over with while loops in Java! Just like a game loop, but smarter. Learn about while loop in Java, control flow...read more

FAQs

What is a do-while loop in Java?

A do-while loop is a control flow statement that executes a block of code at least once and then continues executing it as long as a specified condition remains true.

How does a do-while loop differ from a while loop?

A do-while loop executes its body before checking the condition for the first time, guaranteeing at least one execution, whereas a while loop checks the condition before the first execution.

When should you use a do-while loop?

Use a do-while loop when the code inside the loop needs to run at least once, such as when asking for user input that needs validation.

Can a do-while loop become an infinite loop?

Yes, if the condition always evaluates to true and there is no mechanism within the loop body to break out, it can become an infinite loop.

How do you exit a do-while loop early?

You can exit a do-while loop early by using the break statement within the loop body.

Can you nest do-while loops in Java?

Yes, you can nest do-while loops within other loops including for, while, or other do-while loops.

How does a do-while loop handle boolean expressions?

The do-while loop continues to iterate as long as the boolean expression evaluates to true. Once it evaluates to false, the loop terminates.

What type of loop is the do-while loop considered?

The do-while loop is considered an exit-controlled loop because the condition is checked at the end of the loop body.

Can the condition in a do-while loop use complex expressions?

Yes, the condition in a do-while loop can use complex expressions involving logical, relational, and arithmetic operations.

How does exception handling work within a do-while loop?

Exceptions within a do-while loop work the same as with any block of code. If an exception is thrown and not caught within the loop, it will propagate outward, potentially exiting the loop and being caught by an enclosing try-catch block or causing the program to terminate if uncaught.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio