Home Java Tutorial Java while and do…while Loop

Java while and do…while Loop

by Anup Maurya
28 minutes read

The while and do...while loops in Java allow you to execute a block of code repeatedly as long as a certain condition is true. These loops are commonly used when you need to iterate through a set of values or perform an operation until a certain condition is met.

The while loop

The while loop is the simplest type of loop in Java. It has the following syntax:

while (condition) {
    // statements to be executed repeatedly
}

The condition is an expression that must evaluate to a boolean value (either true or false). The statements inside the loop will be executed repeatedly as long as the condition is true.

Here’s an example of a simple while loop that counts from 1 to 5:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

In this example, the loop initializes a variable i to 1, and then executes the statements inside the loop as long as i is less than or equal to 5. The statements inside the loop simply print out the current value of i, and then increment i by 1.

The output of this program would be:

1
2
3
4
5

The do…while loop

The do...while loop is similar to the while loop, but it guarantees that the statements inside the loop will be executed at least once, even if the condition is initially false.

It has the following syntax:

do {
    // statements to be executed repeatedly
} while (condition);

The condition is checked at the end of each iteration of the loop, after the statements inside the loop have been executed.

Here’s an example of a simple do...while loop that asks the user to enter a number between 1 and 10:

Scanner scanner = new Scanner(System.in);
int number;

do {
    System.out.print("Enter a number between 1 and 10: ");
    number = scanner.nextInt();
} while (number < 1 || number > 10);

System.out.println("You entered " + number);

In this example, the loop repeatedly asks the user to enter a number between 1 and 10 until a valid number is entered. The statements inside the loop print out a prompt to the user and read in a number using a Scanner object. The loop continues as long as the number is less than 1 or greater than 10.

The output of this program would be:

Enter a number between 1 and 10: 0
Enter a number between 1 and 10: 11
Enter a number between 1 and 10: 5
You entered 5

Note that the loop executes once with an invalid input (0 and 11 in this case) before prompting the user for a valid input.

related posts

Leave a Comment

Enable Notifications OK No thanks