Java While and Do-While Loops with Code Examples
In this guide, we will delve into two fundamental types of loops in Java: the while
loop and the do-while
loop. We’ll explore their differences, use cases, and provide illustrative code examples to help you grasp their concepts effectively.
The While Loop
The while
loop is a fundamental construct in Java that allows you to repeatedly execute a block of code as long as a certain condition remains true. It’s particularly useful when you want to execute a code block an unknown number of times based on a condition. Here’s the basic syntax of a while
loop:
while (condition) {
// Code to be executed repeatedly
}
Let’s take a look at an example to better understand how the while
loop works:
public class WhileLoopExample {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
System.out.println("Loop finished");
}
}
In this example, the loop will iterate as long as the count
is less than 5. The count
variable starts at 0 and increments with each iteration, printing the value of count
until it reaches 5.
The Do-While Loop
The do-while
loop is a close cousin of the while
loop but with a slight difference: it guarantees that the loop’s code block will be executed at least once, regardless of the condition. The condition is checked after the execution of the loop’s code block. The syntax of a do-while
loop is as follows:
do {
// Code to be executed repeatedly
} while (condition);
Let’s explore a practical example of the do-while
loop:
import java.util.Scanner;
public class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a number (0 to exit): ");
number = scanner.nextInt();
System.out.println("You entered: " + number);
} while (number != 0);
System.out.println("Loop finished");
}
}
In this example, the loop asks the user to enter a number repeatedly until they input 0
. Even if the user inputs 0
on the first try, the loop’s code block will still execute once before checking the condition.
Choosing Between While and Do-While Loops
Deciding whether to use a while
loop or a do-while
loop depends on your specific use case. Use a while
loop when you want to execute a block of code zero or more times, based on a condition. On the other hand, opt for a do-while
loop when you need to ensure that the loop’s code block executes at least once before checking the condition.
Conclusion
Loops are a crucial part of programming, allowing you to automate repetitive tasks and control the flow of your code. Java’s “while” and “do-while” loops are valuable tools that provide developers with the flexibility to execute code repeatedly based on specific conditions.