Java Do/While Loop
The do/while loop is similar to the while loop, but it guarantees that the loop body is executed at least once because the condition is checked after the loop body.
Key Topics
1. Syntax
The basic syntax of a do/while loop is as follows:
do {
// Code to execute
} while (condition);
2. Example
Example of using a do/while loop:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 2
Count: 3
Count: 4
Count: 5
3. When to Use Do/While Loop
Use a do/while loop when you need to ensure that the loop body executes at least once, such as when prompting a user for input.
Example of prompting user input:
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
do {
System.out.print("Enter a positive number: ");
input = scanner.nextLine();
} while (Integer.parseInt(input) <= 0);
System.out.println("You entered: " + input);
scanner.close();
}
}
Output:
Enter a positive number: -1
Enter a positive number: 0
Enter a positive number: 5
You entered: 5
Key Takeaways
- The
do/whileloop checks the condition after executing the loop body. - Guarantees at least one execution of the loop body.
- Useful for input validation and scenarios where the initial execution is required.