JAVA Do While Loop Example Code
In this post we will discuss Java Do While loop. A Java Do While Loop is similar as it is in C or C++ Language. A Java do while loop is some how different from for loop and while loop. The specialty of do while loop is that , its body gets at least once, even the loop condition is false.
Before we go into details of a do while loop, let us discuss what are loops and why loops are needed in any programming language. The answer to this question is , sometimes in programming we need to repeat a set of statements for a number of times. Writing same code again and again in the same program is difficult for a programmer. Also it increases program length. Suppose in a program , there is need of writing a string "Hello " 100 times. Then we have to write print statement 100 times. Writing print statement 100 times in a single program for the same output is difficult. In that case we can use a loop of 100, and in that case we have to use only a single loop statement.
Print ("hello");
Print ("hello");
-
-
Print ("hello");
The alternative way is use of a for loop.
for (i=1;i<=100;i++)
{
print("Hello");
}
You can see the difference.
Do While Loop
A Java Do while loop executes a set of of Java statements as long as the loop condition evaluates to true.In some programming conditions ,we require a loop that executes at least once before evaluating Boolean condition.
Java Do while loop is Exit Controlled Loop
General Syntax of Java do while loop
The general syntax of a Java do while loop is:
do
{
set of statements to be repeated;
} while(condition);
Example:
class Test { public static void main(String args[]){ int i = 1; do{ System.out.print("value of i : " + i ); i++; System.out.print("\n"); }while( i < 11 ); } }
Usually it is recommended to avoid the use of do-while loop. For loop and while loop are more convenient loops in Java.
Summary
This was all about do while loop in Java.