The do-while loop in Java is a variant of the while loop that ensures the code block inside the loop is executed at least once, regardless of whether the condition is true or false.
This tutorial will cover how the do-while loop works, its syntax, and examples to illustrate different scenarios where it can be used effectively.
Table of Contents:
1. Introduction to do-while Loop
The do-while loop is a control flow statement that executes a block of code once, then checks a condition. If the condition is true, the loop continues executing the block. This ensures that the code inside the loop runs at least once, even if the condition is initially false.
2. Syntax of do-while Loop
General Syntax:
do { // Code to be executed } while (condition);
do: The code inside the do block is executed first.
while: After the execution of the block, the condition is evaluated. If true, the loop repeats; if false, the loop terminates.
3. Basic Example of do-while Loop
Example 1: Basic do-while Loop
public class Main { public static void main(String[] args) { int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 5); } }
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
In this example:
The loop executes the block once, and after each iteration, it checks whether count is still less than or equal to 5.
The loop runs five times and prints the value of count in each iteration.
4. do-while Loop vs while Loop
The key difference between the do-while loop and the while loop is that the do-while loop executes the code at least once, even if the condition is false. In contrast, the while loop evaluates the condition before executing the loop body.
Example 2: do-while vs while Loop
public class Main { public static void main(String[] args) { int count = 10; // Using while loop while (count < 5) { System.out.println("While Loop: Count is " + count); } // Using do-while loop do { System.out.println("Do-While Loop: Count is " + count); } while (count < 5); } }
Output:
Do-While Loop: Count is 10
In this example:
The while loop doesnโt execute because the condition count < 5 is false.
The do-while loop runs once even though the condition is false.
5. Common Use Cases for do-while Loop
The do-while loop is often used when the loop needs to execute at least once, such as in the following scenarios:
Example 3: User Input Validation
A common use case is to prompt the user for input repeatedly until they provide valid input.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number; do { System.out.println("Enter a number between 1 and 10:"); number = scanner.nextInt(); } while (number < 1 || number > 10); System.out.println("You entered: " + number); } }
Output (Example inputs: 12, then 5):
Enter a number between 1 and 10: 12 Enter a number between 1 and 10: 5 You entered: 5
In this example, the do-while loop ensures that the user is prompted at least once, and the loop repeats until the user enters a valid number.
Example 4: Repeated Menu Display
A do-while loop can be useful for repeatedly showing a menu to the user until they choose to exit.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice; do { System.out.println("Menu:"); System.out.println("1. Start"); System.out.println("2. Settings"); System.out.println("3. Exit"); System.out.print("Choose an option: "); choice = scanner.nextInt(); switch (choice) { case 1: System.out.println("Starting..."); break; case 2: System.out.println("Opening settings..."); break; case 3: System.out.println("Exiting..."); break; default: System.out.println("Invalid choice, please try again."); } } while (choice != 3); } }
Output (Example input: 1, then 3):
Menu: 1. Start 2. Settings 3. Exit Choose an option: 1 Starting... Menu: 1. Start 2. Settings 3. Exit Choose an option: 3 Exiting...
In this example, the menu is displayed repeatedly until the user selects the option to exit (choice 3).
6. Using break and continue with do-while
You can use break and continue to control the flow within a do-while loop.
break: Immediately terminates the loop.
continue: Skips the current iteration and moves to the next iteration.
Example 5: Using break with do-while
public class Main { public static void main(String[] args) { int count = 1; do { System.out.println("Count: " + count); if (count == 3) { break; // Exit the loop when count is 3 } count++; } while (count <= 5); } }
Output:
Count: 1 Count: 2 Count: 3
In this example, the loop terminates when count reaches 3 due to the break statement.
Example 6: Using continue with do-while
public class Main { public static void main(String[] args) { int count = 0; do { count++; if (count % 2 == 0) { continue; // Skip even numbers } System.out.println("Odd number: " + count); } while (count < 10); } }
Output:
Odd number: 1 Odd number: 3 Odd number: 5 Odd number: 7 Odd number: 9
In this example, the continue statement skips even numbers and only prints odd numbers.
7. Nested do-while Loops
You can nest one do-while loop inside another to handle more complex scenarios.
Example 7: Nested do-while Loop
public class Main { public static void main(String[] args) { int outer = 1; do { int inner = 1; do { System.out.println("Outer: " + outer + ", Inner: " + inner); inner++; } while (inner <= 2); outer++; } while (outer <= 3); } }
Output:
Outer: 1, Inner: 1 Outer: 1, Inner: 2 Outer: 2, Inner: 1 Outer: 2, Inner: 2 Outer: 3, Inner: 1 Outer: 3, Inner: 2
In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop runs twice.
8. Best Practices for Using do-while Loops
Use do-while when you need the code to run at least once: The do-while loop is useful when the condition check comes after the first execution, ensuring the block runs at least once.
Avoid infinite loops: Always ensure the condition in the while statement will eventually evaluate to false to avoid infinite loops.
Use break and continue wisely: While these keywords provide control over the loop, overusing them can make the code harder to follow.
Maintain readability: If a do-while loop becomes complex or deeply nested, consider refactoring your code to improve readability.
Conclusion
The do-while loop in Java is a powerful control structure that guarantees a block of code will run at least once.
This makes it useful in scenarios like input validation, menu-driven programs, and situations where the logic must be executed before the condition is checked.
Understanding how to effectively use do-while loops, along with break and continue statements, allows you to write more flexible and robust Java programs.