In this tutorial, we will learn how to use while loop in Java with the help of examples and we will also learn about the working of this Loop in computer programming.
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. If the condition evaluates to true then we will execute the body of the loop and go to update expression else we will stop.
while (condition)
{
// code block to be executed
}
// Java program to illustrate
// while loop
public class MyClass
{
public static void main(String[] args)
{
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
}
}
Output :
0
1
2
3
4
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
do
{
// code block to be executed
}
while (condition);
// Java program to illustrate
// do-while loop
public class MyClass
{
public static void main(String[] args)
{
int i = 0;
do
{
System.out.println(i);
i++;
}
while (i < 5);
}
}
Output :
0
1
2
3
4
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!