Learn do while loop in java programming with program examples and explanation. Also, code to run do while loop infinitely included. Know what difference between is while loop and do while loop.
Topics
- Syntax of do -while loop with code example
- Infinite do while loop
- Difference between while and do while loop
A do while loop is like a while loop, except that do while loop executes its body at least once.
Syntax of do while loop in java:
do{
//do something
} while(Boolean_expression);
Example of Do while loop in java
Printing number 1 to 10.
public class Sample {
public static void main(String[] args) {
int n = 1;
do {
System.out.println(n);
++n;
} while (n <= 10);
}
}
Infinite Do While loop
To run a do while loop infinitely, just we need to write true in while condition e.g. do{…}while(true).
public class Sample {
public static void main(String[] args) {
do {
System.out.println("I am running infinitely...");
} while (true);
}
}
Output:
Below string will be printed infinitely.
I am running infinitely…
I am running infinitely…
I am running infinitely…
Difference between while and do while loop
While loop in java may not run a single time when condition of Boolean expression is false. But in do while loop, it’s all statements in the body run at least once, as, control enters the loop first time in do{} and it checks the expression in while condition at the end.