While loop in java

Let’s learn while loop in java.

While loop in java

A while loop iterates a block of statements until condition is true. In a while loop, condition is executed first.

Also read – do while loop example

If expression/condition is true then statements inside while loop is executed until expression is true. Else control passes out of the loop.

Loops are used to execute some block of statements until some expression or condition is evaluated.

Syntax:

while(booleanExpression/condition)
{
   // code goes here
}


while loop in java

NOTE:

while loop can test multiple conditions. For example

while (x > y && z == 2)
{
   // statements/code
}


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

In the above example increment statement (a++) is inside while loop. This is because to end while loop execution.

By doing this variable ‘a’ gets changed on each iteration and at one point returns false.


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

…….

java while loop break

Let’s see program to demonstrate use of break statement in while loop.

public class JavaWhileLoopBreak 
{
   public static void main(String[] args) 
   {
      int a = 1;  
      while(a <= 20)
      {  
         if(a == 6)
         {  
            a++;  
            break; // break the loop  
         }  
         System.out.println(a);  
         a++;  
      }
   }
}



Output:

1
2
3
4
5

Iterate Array using while loop

Now let’s learn to iterate and print integer elements of an array using while loop. Here’s the example,

public class ArrayWhileLoop
{
   public static void main(String[] args) 
   {
      int[] arrNumbers = {2, 4, 6, 8, 10, 12};
      int a = 0;
      System.out.println("Printing even numbers: ");
      while(a < 6)
      {
         System.out.println(arrNumbers[a]);
         a++;
      }
   }
}



Output:

Printing even numbers:
2
4
6
8
10
12