While loop in java

In this post we are going to learn while loop in java.

A while loop run or iterate a block of statements number of times, until condition is true.

In while loop condition is executed first if expression/condition is true then statements inside while loop is executed until expression is true.

If expression/condition is false then control passes out.

Syntax :

while(booleanExpression)
{
   // code goes here
}

while loop in java

public class WhileLoopDemo 
{
   public static void main(String args[])
   {
      int a = 1;
      while(a < 10)
      {
         System.out.println(a);
// increase variable used in condition
// else loop will never end a++;
System.out.print("\n"); } } }

Output :

1
2
3
4
5
6
7
8
9


Java infinite while loop

Now let’s see infinite while loop example,

public class WhileLoopExample 
{
   public static void main(String[] args) 
   {
      boolean value = true;
while(value)
{
System.out.println("Infinite loop");
}
} }

Output:

Infinite loop
Infinite loop
Infinite loop

…….


Also read – if else java