Java tutorials for Beginners – Java while and do…while Loop

(Java programming Example for Beginners)

Java while and do…while Loop

In this tutorial, we will learn how to use while and do while loop in Java with the help of examples and we will also learn about the working of Loop in computer programming

In computer programming, loops are used to repeat a specific block of code until a certain condition is met (test expression is false). For example,

Imagine we need to print a sentence 50 times on your screen. Well, we can do it by using the print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops. With loops, we can simply write the print statement one time and run it for any number of times.

It’s just a simple example showing the importance of loop in computer programming. There are 3 types of loops in Java: for loop, while loop, and do-while loop.


Java while Loop

The syntax of while loop in Java is:

while (testExpression) {
    // codes inside the body of while loop
}

How while loop works?

In the above syntax, the test expression inside parenthesis is a boolean expression. If the test expression is evaluated to true,

  • statements inside the while loop are executed.
  • then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false,

  • the while loop is terminated.

Flowchart of while Loop

Java while loop flowchart
Working of while Loop

Example 1: while Loop

// Program to print line 10 times

class Loop{
    public static void main(String[] args){
      
        int i = 1;
	   
        while (i <= 10) {
            System.out.println("Line " + i);
            ++i;
        }
    }
}

Output:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

In the above example, we have a test expression (i <= 10). It checks whether the value of i is less than or equal to 10.

Here initially, the value of i is 1. So the test expression evaluates to true for the first time. Hence, the print statement inside while loop is executed.

Inside while loop notice the statement

 ++i;

This statement increases the value of i by 1 in each iteration. After 10 iterations, the value of i will be 11. Then, the test expression (i <= 10) evaluates to false and while loop terminates.

 


Example 2: Java while Loop

// Program to find the sum of natural numbers from 1 to 100.

class AssignmentOperator{
    public static void main(String[] args){
      
        int sum = 0, i = 100;
	   
        while (i != 0) {
            sum += i;     // sum = sum + i;
            --i;
        }
	   
        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 5050

Here, we have two variables named sum and i whose initial values are 0 and 100 respectively.

In each iteration of the while loop,

  • the sum variable is assigned value: sum + i
  • the value of i is decreased by 1

The loop continues until the value of i is equal to 0. For better visualization,

1st iteration: i = 100, sum = 0+100 = 100, and  --i = 99
2nd iteration: i = 99, sum = 100+99 = 199, and --i = 98
3rd iteration: i = 98, sum = 199+98 = 297, and --i = 97
... .. ...
... .. ...
99th iteration: i = 2, sum = 5047+2 = 5049, and --i = 1
100th iteration: i = 1, sum = 5049+1 = 5050, and --i = 0

Java do…while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.

Here is the syntax of the do...while loop.

do {
   // codes inside body of do while loop
} while (testExpression);

How do…while loop works?

The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false.

When the test expression is false, the do..while loop terminates.


Flowchart of do…while Loop

Flowchart of do while loop in Java
Working of do…while Loop

Example 3: do…while Loop

The program below calculates the sum of numbers entered by the user until user enters 0.

import java.util.Scanner;

class Sum{
    public static void main(String[] args){
	   
        Double number, sum = 0.0;
        // creates an object of Scanner class
        Scanner input = new Scanner(System.in);

        do {

            // takes input from the user
            System.out.print("Enter a number: ");
            number = input.nextDouble();
            sum += number;
        } while (number != 0.0);  // test expression
	   
        System.out.println("Sum = " + sum);
    }
}

Output:

Enter a number: 2.5
Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0

Infinite while Loop

We should be always careful while working with loops. It is because if we mistakenly set the test expression in such a way that it is never false, the while and do...while loop will run forever.

This is called infinite while and do...while loop. For example,

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

Let’s take another example,

// Infinite while loop
int i = 100;
while (i == 100) {
   System.out.print("Hey!");
}

The infinite do...while loop works in a similar way as while loop.

 

Java tutorials for Beginners – Java while and do…while Loop

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.