Skip to main content

Java Do-While Loop

Introduction to Java Do-While Loop

In Java, loops are used to execute a set of statements repeatedly until a particular condition is satisfied. Among the different types of loops, such as for, while, and do-while, this article focuses on the do-while loop.

The do-while loop is similar to a while loop, but with a key difference: the do-while loop will execute the block of code at least once before checking the condition. This is because the condition is checked after executing the loop body.

Syntax of do-while loop in Java

The syntax of a do-while loop in Java is as follows:

do {
// code block to be executed
} while (condition);

In this syntax, the code block within the do {...} brackets is the code that will be executed. The while (condition) checks whether the condition is true. If the condition is true, the loop will continue to execute. If the condition is false, the loop will stop.

Remember, the condition is checked after the loop has been executed, so the loop will always run at least once, even if the condition is false.

Example of a do-while loop

Here is a simple example of a do-while loop in action:

int i = 1;

do {
System.out.println(i);
i++;
} while (i <= 5);

In this example, the loop will print the values from 1 to 5. Even though the condition is checked after the loop executes, in this case, the condition i <= 5 is initially true, so the loop continues until i is no longer less than or equal to 5.

When to use a do-while loop

A do-while loop is particularly useful when you want a block of code to run at least once. For instance, in a program where you want to display a menu to a user at least once and keep displaying it until the user chooses to exit, a do-while loop would be a good choice.

Here is a simple example that demonstrates this:

import java.util.Scanner;

int choice;

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

Scanner s = new Scanner(System.in);
choice = s.nextInt();

// process the choice
// ...

} while (choice != 3);

In this example, the menu is displayed at least once and continues to be displayed until the user enters 3 to exit.

Conclusion

To summarize, the do-while loop is a control flow statement that allows a block of code to be executed repeatedly based on a given condition. The key feature of a do-while loop is that the loop will be executed at least once because the condition is checked after the loop body is executed. This makes do-while loops ideal for situations where the loop body needs to be executed at least once.