while loop in java

Let’s learn while loop in java.

while loop in java

A while loop continuously executes statement or group of statements until the condition is true.

While loop in java

Syntax:

while(condition)
{
   // body
}

The while loop syntax as you can see its got the while keyword, then there’s a condition in parentheses which should be of boolean type and loop body.


While loop in java example:

public class WhileLoopDemo
{
   public static void main(String args[])
   {
      int a = 1;
      while(a < 10)
      {
         System.out.println(a);
         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. Because to end while loop execution. By doing this integer variable ‘a’ gets incremented on each iteration and at one point returns false.


Infinite while loop

Now let’s see an example on infinite while loop.

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 on iterate array using while loop.

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


Also read – classes and objects in java