🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. Unlike the while loop, the do-while loop guarantees that the code block is executed at least once before the condition is tested. This makes the do-while loop particularly useful for scenarios where you need to ensure that the code block executes at least once.
Table of Contents
- What is a do-while Loop?
- Syntax of do-while Loop
- How do-while Loop Works
- Simple do-while Loop Example
- Infinite do-while Loop
- do-while Loop with a Break Statement
- do-while Loop with a Continue Statement
- Nested do-while Loop
- Using a do-while Loop for Input Validation
- Conclusion
What is a do-while Loop?
A do-while loop repeatedly executes a block of code as long as the specified condition evaluates to true. The key difference from a while loop is that the condition is evaluated after the loop body, ensuring that the loop body is executed at least once.
Syntax of do-while Loop
Syntax:
do {
// body of loop
} while (condition);
- condition: A boolean expression that is evaluated after each iteration of the loop.
- body of loop: The block of code that is executed at least once and as long as the condition is true.
How do-while Loop Works
- The loop body is executed.
- The condition is evaluated.
- If the condition is true, the loop body is executed again.
- Steps 2 and 3 are repeated until the condition becomes false.
- When the condition is false, the loop terminates, and control moves to the next statement after the loop.
Simple do-while Loop Example
Example:
public class SimpleDoWhileLoop {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 5);
}
}
Explanation: This loop prints the numbers from 1 to 5. The body of the loop is executed first, and then the condition count <= 5 is checked. Since the condition is true, the loop continues to execute until count exceeds 5.
Infinite do-while Loop
An infinite loop occurs when the condition always evaluates to true.
Example:
public class InfiniteDoWhileLoop {
public static void main(String[] args) {
do {
System.out.println("This is an infinite loop");
} while (true);
}
}
Explanation: This loop will print "This is an infinite loop" indefinitely because the condition true never changes.
do-while Loop with a Break Statement
The break statement can be used to exit the loop prematurely.
Example:
public class DoWhileWithBreak {
public static void main(String[] args) {
int count = 1;
do {
if (count == 5) {
break;
}
System.out.println("Count: " + count);
count++;
} while (count <= 10);
}
}
Explanation: This loop prints numbers from 1 to 4. When count equals 5, the break statement exits the loop.
do-while Loop with a Continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
Example:
public class DoWhileWithContinue {
public static void main(String[] args) {
int count = 0;
do {
count++;
if (count % 2 == 0) {
continue;
}
System.out.println("Odd number: " + count);
} while (count < 10);
}
}
Explanation: This loop prints odd numbers from 1 to 9. The continue statement skips the even numbers.
Nested do-while Loop
A nested do-while loop is a do-while loop inside another do-while loop, useful for iterating over multidimensional structures.
Example:
public class NestedDoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.println("i: " + i + ", j: " + j);
j++;
} while (j <= 3);
i++;
} while (i <= 3);
}
}
Explanation: This loop prints pairs of i and j values, iterating over all combinations of i and j from 1 to 3.
Using a do-while Loop for Input Validation
The do-while loop is often used for validating user input.
Example:
import java.util.Scanner;
public class InputValidation {
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();
if (number <= 0) {
System.out.println("Invalid input. Please try again.");
}
} while (number <= 0);
System.out.println("You entered: " + number);
scanner.close();
}
}
Explanation: This loop repeatedly prompts the user to enter a positive number until a valid input is provided.
Conclusion
The do-while loop in Java is a powerful control flow statement for performing repeated tasks based on a condition. Unlike the while loop, the do-while loop guarantees that the code block is executed at least once. Understanding how to use the do-while loop effectively, including its variations with break and continue statements, as well as nested loops, is essential for writing robust and efficient Java programs.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment