Java do-while loop with Examples
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Loops are essential constructs in Java. They facilitate the execution of a specific block of code either for a predetermined number of iterations or until a certain condition is satisfied. Three primary loop structures come to the fore in Java: the for loop, the while loop, and the do-while loop.
Among these, the do-while loop holds a distinctive position, providing a unique approach to code repetition. Unlike the for and while loops, the do-while loop ensures that a designated code block is executed at least once before assessing the loop’s condition. This peculiarity makes it a valuable tool for scenarios in which an initial, mandatory execution is required, regardless of the outcome of the test condition.
In this article, we will explore the do-while loop in Java, exploring its features, use cases, and advantages. By the end, you will have a comprehensive understanding of when and how to employ the do-while loop effectively in your Java programs, enhancing their flexibility and functionality.
Syntax of the Java do-while Loop
The syntax of the Java do-while loop is:
do { // code block } while (test_expression);
- The loop body contains code to execute repeatedly
- Update expression to increment/decrement loop variable
- Condition check to determine if another iteration is required
The test_expression must be evaluated using a boolean value, either true or false. It controls when the loop terminates.
Components of the do-while Loop in Java
- Test Expression – Evaluate a condition that controls the termination of the loop. Example: i <= 10
- Update Expression – Used to increment or decrement the loop variable. Example: i++
Step-by-step execution of the Java do-while loop
1. Control enters the loop
2. Statements in loop body are executed
3. Loop variable is updated via update expression
4. Condition check takes place
5. If condition is true, control goes back to loop body
6. If condition is false, loop terminates
7. Control flow moves out of loop
Illustration of the Java do-while Loop
public class DoWhileExample { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while (i < 1); } }
Output:
1
Though the test condition is false, the print statement executes once since the do-while checks the condition after the loop body.
Implementation Examples
Example 1: Printing “DataFlair” 5 times
public class DoWhileExample { public static void main(String[] args) { int i = 1; do { System.out.println("DataFlair"); i++; } while (i <= 5); } }
Output:
DataFlair
DataFlair
DataFlair
DataFlair
DataFlair
Example 2: Finding the summation of numbers from 1 to 100
public class SumExample { public static void main(String[] args) { int sum = 0; int i = 1; do { sum += i; i++; } while (i <= 100); System.out.println("The sum of numbers from 1 to 100 is: " + sum); } }
Output:
The sum of numbers from 1 to 100 is: 5050
Example 3: do-while loop without curly braces {}
public class DoWhileWithoutBracesExample { public static void main(String[] args) { int i = 1; do System.out.println("Iteration " + i); while (i <= 5); } }
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Application of the do-while Loop in Java
1. Menu Systems: Implementing interactive menus in software applications where the menu is displayed to the user at least once, ensuring they can choose further interaction.
2. Input Validation: Validating user input by repeatedly prompting the user until they enter valid data, ensuring the program doesn’t proceed with incorrect or invalid input.
3. Game Loops: In game development, the do-while loop is often used for game loops. This loop ensures that the game logic and rendering are executed at least once per frame before checking for conditions like game over.
4. Data Processing: Processing data or records, especially in batch processing scenarios, where you want to process each record until the end of the dataset is reached.
5. File Reading/Writing: Read or write data to and from files, ensuring data integrity by performing at least one read or write operation before checking for the end of the file or completion.
Conclusion
In summary, the do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition. This feature is precious in scenarios where you must guarantee an initial execution, such as interactive menus or game development.
Unlike the standard while loop, which evaluates the test condition first, the do-while loop executes the code block before checking the condition. This characteristic makes it an essential choice in scenarios where this post-condition execution is required, simplifying the coding process and ensuring a smoother user experience.
Did you like this article? If Yes, please give DataFlair 5 Stars on Google