While loop in java

Let’s learn while loop in java.

While loop in java

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

Also read – classes and objects in java

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

Java while loop example

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

…….