While loop in java

Let’s learn while loop in java.

While loop in java

A while loop checks the condition at start before executing the code block. In a while loop condition is executed first.

While loop in java

If a condition is true then statements inside while loop is executed. Else program control passes out of the loop.

Looping statements in java are used to execute some block of statements until some expression or condition is evaluated.

Syntax:

while(condition)
{
   // code goes here
}

The while loop syntax as you can see its got the while keyword, then there’s a condition in parentheses then we have a code block and this loop executes if the condition is true.

NOTE:

  • While loop just has a condition. If we want to increment a variable then we have to do it manually inside the loop.
  • If we want to use a variable in the condition then we have to declare that variable outside of while loop.
  • We should be careful with conditions. Because it is easy to end up with infinite or endless loop that never executes.

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