Java while and do...while Loop



In this tutorial, we will learn how to use the while and the do...while loop in Java with the help of examples.

Loops are usually used to repeat a block of code as long as a specified condition is true. For example, if we want to repeat an action 10 times, we can simply use a loop.

In the previous tutorial, we learned about Java for loop. Here, we are going to learn about while and do...while loops.


Java while Loop

Java while loop is used to loop through a block of code as long as a specified condition is met.

The syntax of the while loop can be given as follows:

while(condition) {
    // body of loop
}

Here,

  • A while loop evaluates the condition inside the parenthesis ().
  • If the condition evaluates to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition evaluates to false, the loop stops.

How does a Java while loop works?

The following illustration demonstrates how the Java while loop works.

Flowchart of the Java while Loop

Example: Display Numbers from 1 to 4

In the following example, we will use the while loop to print numbers from 1 to 4.

public class Main{
    public static void main(String[] args){
        
        int i = 1, n = 4;

        while(i <= n) {
            System.out.println(i);
            i++;
        }
    }
}

Output

1
2
3
4

Here is how the above program works.

Iteration Variable Condition: i <= n Action
1st i = 1 n = 5 true 1 is printed. i is increased to 2.
2nd i = 2 n = 5 true 2 is printed. i is increased to 3.
3rd i = 3 n = 5 true 3 is printed. i is increased to 4.
4th i = 4 n = 5 true 4 is printed. i is increased to 5.
5th i = 6 n = 5 true The loop is terminated.

Example: Calculating the Sum of Positive Numbers

In the following example, we will use the Scanner class to take input from the user.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int sum = 0;
        
        // creating an object of Scanner class
        Scanner input = new Scanner(System.in);
        
        // taking integer input from the user
        System.out.println("Enter a positive number : ");
        int number = input.nextInt();

        while(number >= 0) {
            sum += number;

            System.out.println("Enter a positive number : ");
            number = input.nextInt();
        }

        System.out.println("Sum = " + sum);
        input.close();
    }
}

Output

Enter a positive number : 
12
Enter a positive number : 
27
Enter a positive number : 
8
Enter a positive number : 
4
Enter a positive number : 
-9
Sum = 51

In the above program, we have used the nextInt() method to take integer input from the user.

The while loop continues until the user enters a negative number. Through each iteration, the number entered by the user is added to the sum variable.

The loop terminates when the user enters a negative number. And finally, the total sum is displayed.


Java do...while loop

The do...while loop is the same as the while loop. However, the body of do...while loop is executed once before the condition is checked.

The syntax of the do...while can be given as follows.

do {
    // body of loop
} while(testCondition);

Here,

  • The body of the loop is executed at first. Then the testCondition is evaluated.
  • If the testCondition evaluates to true, the loop's body inside the do....while is executed again.
  • The testCondition is evaluated once again.
  • If the testCondition evaluates to true, the loop's body inside the do...while is executed again.
  • The process continues until the testCondition evaluates to false. Then the loop stops.

How does a Java do...while loop works?

The following illustration demonstrates how the Java do...while loop works.

Flowchart of the Java do...while Loop

Example: Display Numbers from 1 to 4

In the following example, we will use the do...while loop to print numbers from 1 to 4.

public class Main{
    public static void main(String[] args){
        
        int i = 1, n = 4;

        do {
            System.out.println(i);
            i++;
        } while(i <= n);
    }
}

Output

1
2
3
4

Here is how the above program works.

Iteration Variable Condition: i <= n Action
i = 1 n = 4 not checked 1 is printed. i is increased to 2.
1st i = 2 n = 4 true 2 is printed. i is increased to 3.
2nd i = 3 n = 4 true 3 is printed. i is increased to 4.
3rd i = 4 n = 4 true 4 is printed. i is increased to 5.
4th i = 5 n = 4 false The loop is terminated.

Example: Calculating the Sum of Positive Numbers

In the following example, we will use the Scanner class to take input from the user.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int sum = 0;
        int number = 0;
        
        // creating an object of Scanner class
        Scanner input = new Scanner(System.in);

        do {
            System.out.println("Enter a positive number : ");
            number = input.nextInt();

            sum += number;
        } while(number >= 0);

        System.out.println("Sum = " + sum);
        input.close();
    }
}

Output

Enter a positive number : 
18
Enter a positive number : 
9
Enter a positive number : 
7
Enter a positive number : 
3
Enter a positive number : 
-4
Sum = 33

As we can see above, when the user enters a positive number, the number is added to the sum variable. And this process continues until the entered number is negative.


Infinite while loop

To make a loop runs for infinite times, we need to make the test condition always true. For example,

// infinite while loop
while(true) {
    // body of loop
}

We can also create an infinite do...while loop.

// infinite do...while loop
do {

} while(true);

Note: The infinite loop can run forever until the memory is full.


Difference between for and while loops

The for loop is generally used when the number of iterations is known. For example,

for(int i = 0; i <= 10; i++) {
    // body of loop
}

The while and do...while loops are generally used when the number of iterations is known. For example,

while(testCondition) {
    // body of loop
}


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.