[post-views]
In this lesson, you will learn
A do-while loop in Java is similar to a while loop, but with one key difference: the do-while loop guarantees that the loop body will be executed at least once.
This is because the condition check occurs after the execution of the loop’s body.
Syntax
do {
// Statements to be executed
} while (condition);
Here, the condition is a boolean expression that is evaluated after the loop body is executed.
If the condition is true, the loop will execute again. If it’s false, the loop terminates.
package ControlStatements;
public class BasicCounterDoWhile {
public static void main(String[] args) {
int counter = 0;
do {
System.out.println("Counter is: " + counter);
counter++;
} while (counter < 5);
}
}
Output
Counter is: 0
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
package ControlStatements;
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.println("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
scanner.close();
}
}
Output
Enter a positive number:
-4
Enter a positive number:
-1
Enter a positive number:
1
You entered: 1
This loop will repeatedly ask the user for a positive number until one is entered.
Here’s a summary table highlighting the key differences between a while loop and a do-while loop in Java.
| spect | While Loop | Do-While Loop |
|---|---|---|
| Syntax | while (condition) { // Statements } |
do { // Statements } while (condition); |
| Condition Check | At the beginning of the loop | At the end of the loop |
| Execution | The loop may not execute at all if the initial condition is not met. | The loop executes at least once regardless of the initial condition. |
| Use Case | When it’s necessary to check the condition before executing the loop body. | When it’s necessary to execute the loop body at least once before checking the condition. |
package ControlStatements;
import java.util.Scanner;
public class MenuSelection {
public static void main(String[] args) {
int choice;
do {
System.out.println("1. Option An2. Option Bn3. Exit");
System.out.println("Choose an option: ");
Scanner scanner = new Scanner(System.in);
choice = scanner.nextInt();
// Process the choice
} while (choice != 3);
}
}
Output
1. Option A
2. Option B
3. Exit
Choose an option:
1
1. Option A
2. Option B
3. Exit
Choose an option:
3
This loop displays a menu and processes user input until the user selects the option to exit.
package ControlStatements;
public class ReverseString {
public static void main(String[] args) {
String str = "Hello";
String reversed = "";
int i = str.length() - 1;
do {
reversed += str.charAt(i);
i--;
} while (i >= 0);
System.out.println("Reversed string: " + reversed);
}
}
Output
Reversed string: olleH
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.