While Loop in Java


While loop is the most basic loop statement in Java.It repeats a statement or block when the controlling expression is true. Here is its general form:

while(condition)
{
  //body of loop
}

While Loop Example 1

In the following example, the condition applied inside the while loop is that the value of 'i' will continue until the value is greater than 10 and the value of 'i' will increase by 1 each time the loop continues.

Program
public class Main
{
	public static void main(String[] args) 
	{
		int i=1;
		while(i<=10)  //condition
		{
		    System.out.println(i);
		    ++i;
		}
	}
}
Run

While Loop Example 2

In the example below, we have found out all the even numbers between 10-50. Here min = 10, max = 50 values are taken from the beginning. While I have conditioned the loop that if the min number is more than the max number then it will exit the loop otherwise the loop will continue Each time the loop runs, the value of the min number will be incremented by 1.

Program
public class Main
{
	public static void main(String[] args) 
	{
		int min=10;
		int max=50;
		System.out.println("Even numbers are ");
		while(min<=max)  //condition
		{
		    if(min%2==0)
		    {
		      System.out.println(min);  
		    }
		    ++min;
		}
	}
}
Run

While Loop without body

The body of the while can be empty. This is because a null statement is syntactically valid in Java.

Program
public class Main
{
	public static void main(String[] args) 
	{
		int a=100;
		int b=200;
		//find midpoint between a and b
		while(++a < --b); //no body in this loop
		System.out.println("Midpoint is "+b);
	}
}
Run