English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java while and do...while loops

In this tutorial, we will learn how to use while and do...while loops in Java with examples, and we will also learn how while loops work in computer programming

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

Imagine that we need to print a sentence on the screen5times. Well, we can use the print statement5times (without using loops). How about if you need to print a million sentences? You need to use loops. With loops, we can write the print statement only once and then run it any number of times.

This is just a simple example to show the importance of loops in computer programming. In Java, you can do this3types of loops:for loop, while loop and do-while loop.

Java while Loops

The syntax of the while loop in Java is:

while (testExpression) {
    // The code inside the while loop body
}

How does the while loop work?

In the above syntax, the parentheses insideTestThe expression (testExpression) is a boolean expression. If the calculation result of the test expression (testExpression) is true,

  • The statements inside the while loop will be executed.

  • Then, the test expression (testExpression) is evaluated again.

This process continues until the test expression is evaluated as false. If the calculation result of the test expression is false,

  • Then the while loop is terminated.

While loop flowchart

How the while loop works

Example1: while loop

//The program prints lines10times
class Loop {
    public static void main(String[] args) {
      
        int i = 1;
	   
        while (i <= 10) {
            System.out.println("Line\t" + 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 if the value of i is less than or equal to10.

Initially, the value of i at this point is1. Therefore, the calculation result of the test expression (testExpression) is true. Therefore, the print statement inside the while loop will be executed.

Please note the statements inside the while loop

 ++i;

. The statement increases the value of i by1iterations, the value of i is10After11. Then test the expression (i <= 10)is false, the sum while loop terminates.

For more information on test expressions and their evaluation methods, please visitJava relational operatorsandJava logical operators.

Example2: Java while loop

//programming to find1to10The sum of natural numbers between 0.
class AssignmentOperator {
    public static void main(String[] args) {
      
        int sum = 0, i = 100;
	   
        while (i != 0) {
            sum += i;     // Is equivalent to sum = sum + i;
            --i;
        }
	   
        System.out.println("Sum = " + sum);
    }
}

Output

Sum = 5050

Here, we have two variables named sum, i, with initial values of 0 and100.

In each iteration of the while loop,

  • Assign a value to the sum variable: sum + i

  • The value of i decreases1

The loop continues until the value of i equals 0.

1st repetition: i = 100, sum = 0+100 = 100, at the same time --i = 99
2nd repetition: i = 99, sum = 100+99 = 199, at the same time --i = 98
3rd repetition: i = 98, sum = 199+98 = 297, at the same time --i = 97
... .. ...
... .. ...
99th repetition: i = 2, sum = 5047+2 = 5049, at the same time --i = 1
100th repetition: i = 1, sum = 5049+1 = 5050, at the same time --i = 0

Java do...while loop

The do...while loop is similar to the while loop, but there is a key difference: the loop body is executed once before checking the test expression.

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

do {
   // Code within the do...while loop
} while (testExpression);

How does the do...while loop work?

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

If the test expression is calculated as true, the code in the loop body is executed, and the test expression is calculated again. This process continues until the test expression is calculated as false.

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

Flowchart of do ... while loop

Flowchart of do ... while loop

Example3: do ... while loop

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

To accept the user's input, we use the Scanner object. For more information about Scanner, please visitJava Scanner.

import java.util.Scanner;
class Sum {
    public static void main(String[] args) {
	   
        Double number, sum = 0.0;
        //Create an object of the Scanner class
        Scanner input = new Scanner(System.in);
        do {
            //Accept the user's input
            System.out.print("Please 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 loop

We should always be careful when using loops. This is because if we set the test expression incorrectly so that it never becomes false, then the while and do ... while loops will run indefinitely.

This is what is called infinite while and do...while loops. For example,

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

Let's take another example

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

The working principle of the infinite do...while loop is similar to that of the while loop.