05.Java While and Do
05.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.
In the previous tutorial, you learned about Java for loop. Here, you are going to
learn about while and do...while loops.
while (testExpression) {
// body of loop
}
Here,
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
Output
1
2
3
4
5
i = 1 1 is printed.
1st true
n = 5 i is increased to 2.
i = 2 2 is printed.
2nd true
n = 5 i is increased to 3.
i = 3 3 is printed.
3rd true
n = 5 i is increased to 4.
i = 4 4 is printed.
4th true
n = 5 i is increased to 5.
i = 5 5 is printed.
5th true
n = 5 i is increased to 6.
i = 6
6th false The loop is terminated
n = 5
class Main {
public static void main(String[] args) {
System.out.println("Enter a number");
number = input.nextInt();
}
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
In the above program, we have used the Scanner class to take input from the
user. Here, nextInt() takes integer input from the user.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the
total sum is displayed.
do {
// body of loop
} while(textExpression);
Here,
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
Output
1
2
3
4
5
i = 1 1 is printed.
not checked
n = 5 i is increased to 2.
i = 2 2 is printed.
1st true
n = 5 i is increased to 3.
i = 3 3 is printed.
2nd true
n = 5 i is increased to 4.
i = 4 4 is printed.
3rd true
n = 5 i is increased to 5.
i = 5 6 is printed.
4th true
n = 5 i is increased to 6.
i = 6
5th false The loop is terminated
n = 5
class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
Output 1
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
Enter a number
-8
Sum is 0
Here, the user enters a negative number. The test condition will be false but
the code inside of the loop executes once.
If the condition of a loop is always true , the loop runs for infinite times (until
the memory is full). For example,
In the above programs, the textExpression is always true . Hence, the loop
body will run for infinite times.
And while and do...while loops are generally used when the number of
iterations is unknown. For example,
while (condition) {
// body of loop
}