In this tutorial we will discuss while loop and do while loop.
Java while Loop
A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of while loop is:
while (Expression) {
// codes inside body of while loop
}
How while loop works?
The 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, while loop is terminated.
Flowchart of while Loop

Example: while Loop
// Program to print Hello 10 times
class WhileLoop {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println("Hello " + i);
++i;
}
}
}
The output will be:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
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.
The major difference between While and do While is that statement will be executed at least once in do while.
The syntax of do-while loop is:
do {
// statements
} while (expression);
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

Example: do-while Loop:
class DoWhileLoopDemo {
public static void main(String args[]){
int i=5;
do{
System.out.println(i);
i--;
}while(i>0);
}
}
output:
5
4
3
2
1
Example: Iterating array using do-while loop
class DoWhileArr{
public static void main(String args[]){
int arr[]={21,17,45,90};
//in java array index start with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}
Output:
21
17
45
90
Infinite while and do-while loop
If the test expression never evaluates to false, the body of while and do..while loop is executed infinite number of times.For example,
while (true) {
// body of while loop
}
Example of infinite while and do-while loop
int i = 10;
while (i == 10) {
System.out.print("HelloTech!");
}
output:
HelloTech!
HelloTech!
HelloTech!
ctrl+c
The infinite do-while loop works in similar way like while loop.
int i = 10;
do {
System.out.print("HelloTech!");
}(i == 10);
output:
HelloTech!
HelloTech!
HelloTech!
ctrl+c
You need to press ctrl+c to exit from the program.