What is do-while Loop in Java? (Explained With Examples)

What is do-while Loop in Java?

    Introduction

    In Java, loops are control flow statements that allow code to be executed repeatedly based on a condition. Java provides several types of loops: for, while, and do-while. Among these, the do-while loop stands out because it guarantees the execution of the loop body at least once, making it ideal for scenarios where an action must be taken before checking a condition.

    What is do-while Loop in Java?

    The do-while loop is considered a post-test loop since the condition is evaluated after the loop body has executed. This feature makes it useful in real-world applications like menu-driven programs, input validation, and retry mechanisms.

    Syntax of do-while Loop

    java

    Copy

    Edit

    do {

       // block of statements

    } while (condition);

    ? Explanation:

    do: Starts the loop.

    {}: Contains the code to be executed.

    while(condition): After the first execution, the condition is checked. If true, the loop repeats.

    Important: Don’t forget the semicolon (;) after while(condition)—this is a common syntax mistake.

    Flowchart of do-while Loop

    plaintext

    Copy

    Edit

         ┌──────────────┐

         │ Statement │

         └─────┬────────┘

                 ↓

         ┌────────────┐

         │ Condition │

         └─────┬──────┘

                ↓ Yes

            ┌──────┐

               ↓ ↑

           Repeat ──┘

                ↑ No

              Exit

    As shown in the flowchart, the statement block is executed before the condition is checked.

    Characteristics of do-while Loop

    •  Guaranteed Execution: The code inside the do block is always executed at least once.
    •  Post-condition Check: The condition is evaluated after execution.
    •  Controlled Iteration: Useful for repeat-until scenarios.
    •  Flexible Input Handling: Often used to handle user input validation.

    How do-while Differs from Other Loops

    Loop Type Condition Checked Executes At Least Once Use Case
    for Before No Counting, known iterations
    while Before No Condition-based
    do-while After Yes Must-run-once situations

    Real-world Analogy: Imagine you're tasting soup. You taste first (do), then check if it needs salt (while). If it needs salt, you repeat the process.

    Basic Example

    Let’s start with a simple program that prints numbers from 1 to 5 using a do-while loop.

    java

    Copy

    Edit

    public class DoWhileExample {

      public static void main(String[] args) {

        int i = 1;

        do {

           System.out.println("Number: " + i);

           i++;

         } while (i <= 5);

       }

    }

    Output:

    javascript

    Copy

    Edit

    Number: 1

    Number: 2

    Number: 3

    Number: 4

    Number: 5

    Explanation:

    The loop starts by executing System.out.println("Number: " + i);

    Then it increments i and checks if i <= 5.

    If true, the loop continues. Otherwise, it stops.

    Using do-while Loop with User Input

    This type of loop is ideal for validating user input—prompting the user until they enter a correct value.

    Example: Accepting only positive numbers

    java

    Copy

    Edit

    import java.util.Scanner;

    public class PositiveInput {

       public static void main(String[] args) {

          Scanner sc = new Scanner(System.in);

          int number;

          do {

             System.out.print("Enter a positive number: ");

             number = sc.nextInt();

          } while (number <= 0);

          System.out.println("You entered: " + number);

       }

    }

    Explanation:

    The loop prompts the user to enter a number.

    It continues until a positive number is entered.

    This guarantees at least one input prompt.

    Nested do-while Loop

    You can use a do-while loop inside another do-while loop.

    Example: Displaying a multiplication table (1 to 3)

    java

    Copy

    Edit

    public class NestedDoWhile {

       public static void main(String[] args) {

          int i = 1;

          do {

             int j = 1;

             do {

            System.out.print((i * j) + "\t");

            j++;

          } while (j <= 5);

          System.out.println();

         i++;

       } while (i <= 3);

      }

    }

    Output:

    Copy

    Edit

    1   2   3   4    5

    2   4   6   8   10

    3   6   9  12  15

    Explanation:

    Outer loop iterates for rows (1 to 3)

    Inner loop prints the multiplication values

    Common Mistakes and Debugging

    ? Infinite Loops

    java

    Copy

    Edit

    int i = 1;

    do {

        System.out.println(i);

        // i++; // forgot to increment

    } while (i <= 5);

    This causes an infinite loop since i never increases.

    ❌ Missing Semicolon

    java

    Copy

    Edit

    do {

        System.out.println("Hello");

    } while (true) // missing semicolon here!

    You’ll get a syntax error. Correct way:

    java

    Copy

    Edit

    } while (true);

    ? Tip: Always test your condition carefully and include increment/decrement logic to avoid logical bugs.

    do-while with Arrays

    The do-while loop can be used to iterate through arrays, although it's more common to use for or while.

    Example: Print array values

    java

    Copy

    Edit

    public class ArrayDoWhile {

       public static void main(String[] args) {

         int[] numbers = {10, 20, 30, 40, 50};

         int i = 0;

         do {

            System.out.println(numbers[i]);

            i++;

         } while (i < numbers.length);

       }

    }

    Explanation:

    do-while starts from index 0.

    Runs until i reaches the array length.

    do-while in Menu-Driven Programs

    Menu-based programs often use do-while to keep displaying the menu until the user decides to exit.

    Example: Simple Calculator

    java

    Copy

    Edit

    import java.util.Scanner;

      public class MenuCalculator {

        public static void main(String[] args) {

           Scanner sc = new Scanner(System.in);

           int choice;

           do {

             System.out.println("Menu:");

             System.out.println("1. Add");

             System.out.println("2. Subtract");

             System.out.println("3. Exit");

             System.out.print("Enter choice: ");

             choice = sc.nextInt();

             switch (choice) {

               case 1:

                 System.out.println("Result: " + (10 + 5));

                 break;

               case 2:

                 System.out.println("Result: " + (10 - 5));

                 break;

               case 3:

                  System.out.println("Exiting...");

                  break;

               default:

                  System.out.println("Invalid choice!");

             }

          } while (choice != 3);

       }

    }

    Performance Considerations

    Use do-while only when necessary—i.e., when at least one execution is required.

    For known iteration counts, prefer for loop.

    Avoid using do-while for indefinite processes without exit conditions.

    Interview Questions Related to do-while

    Q1. What is the difference between while and do-while?

    A: do-while executes the block first, then checks the condition. while checks the condition first.

    Q2. Will this run?

    java

    Copy

    Edit

    int i = 10;

    do {

       System.out.println("Hello");

    } while (i < 5);

    A: Yes. It prints "Hello" once since the body runs before the condition is checked.

    Advanced do-while Use Cases

    Simulate a countdown with delay

    java

    Copy

    Edit

    public class Countdown {

       public static void main(String[] args) throws InterruptedException {

         int i = 5;

         do {

             System.out.println("Countdown: " + i);

             Thread.sleep(1000); // 1-second delay

             i--;

          } while (i > 0);

          System.out.println("Go!");

       }

    }

    Game Loop Concept

    Game engines or simple animations often use do-while for loops that run until an exit condition is met.

    Best Practices

    Ensure the exit condition is reachable.

    Use only when one-time execution is mandatory.

    Don’t misuse for standard iteration patterns better suited for for or while.

    Summary

    The do-while loop in Java is a powerful tool when you want your block of code to execute at least once before checking a condition. It’s commonly used in user input validation, menu-based systems, and retry loops. However, its misuse can lead to infinite loops and unreadable code.

    Key Points:

    •  Always executes at least once
    •  Condition is checked at the end
    •  Use semicolon after while(condition);

    FAQs

    Q: Can do-while be used with arrays?

    Yes, although it’s less common, you can iterate through arrays using do-while.

    Q: What happens if the condition is false initiallyinitially?

    The block still executes once before the condition is evaluated.

    Q: Can I nest do-while loops?

    Yes, nesting is possible just like other loops.


    Also Read:

    Post a Comment

    0 Comments