The Java do-while loop is a control flow statement, used to iterate a part of the program several times. this loop is preferred when the number of iteration is not fixed and you must have to execute the loop at least once.
In the do-while loop, statements inside will be executed at least once because the condition is checked after the loop body.
See Also: Java: Types of Looping Statements
Syntax:
do{
//code to be executed
}while(condition);
Flow chart of do-while loop
Example: Prints Even numbers between 1 to 20.
The same example writes in for and while loop also in a different way.
public class DoWhileLoopExample { public static void main(String[] args) { int i=1; System.out.println("Even numbers between 1 to 20:"); do{ if(i%2==0) { // If modulus of number after devision 2 is 0 then even number System.out.println(i); } i++; while(i<=20); } }
Output:
Even nmbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20
Java Infinitive do-while Loop
If you pass true or condition satisfied always as true in the do-while loop, it will be execute infinitive times.
Syntax:
do{
//code to be executed
}while(true);
Example: do-while infinite loop
public class DoWhileInfiniteLoopExample { public static void main(String[] args) { do{ System.out.println("FacingissuesOnIT"); }while(true); } }
Output:
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............
ctrl+c
Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.
You must log in to post a comment.