While Loop in Java | Example Program

The while loop in Java is the most fundamental loop statement that repeats a statement or series of statements as long as the specified conditional expression evaluates to true.

In other words, a while loop repeats the body of the loop as long as the loop condition holds. Each repetition of the body of loop is called iteration.

Java while loop is the simplest of all the looping structures. It is an entry-controlled loop statement.

In the entry-controlled loop, the test condition evaluates first. If the specified condition is true, then the body of loop executes.

If the conditional expression does not satisfy, then the body of loop will not execute.

Syntax of While Loop in Java


A while loop is the most fundamental loop statement in Java. It executes statements repeatedly while the test condition is true. The general syntax for using the while loop in java program is as follows:

Initialization;
while(test condition) 
{
  // Loop body
     Statement(s);
     Increment/Decrement;
}

In the above syntax, while is a keyword. The test condition can be any boolean expression, which returns either true or false. This condition evaluates before statements execute. This boolean expression controls the execution of the loop body.

When the test condition is true, then the body of loop (statements) will execute. After the execution of loop body, the test condition once again evaluates to true.

If the specified condition is true, the loop body executes once again. This process of repeated execution of loop body continues until the conditional expression finally becomes false.

Once the conditional expression is false, the loop is terminated and the control of execution transfers out of the loop.

On exit, the program continues with the next statement immediately after closing curly braces of while loop. Each execution of the loop body refers to as an iteration (or repetition).

The part of the loop that contains statements to be executed repeatedly is called the loop body. A loop body may contain one or more statements.

Curly braces are required only if the loop body has two or more statements. However, it is good programming practice to use curly braces even if the loop body contains only one statement.

Flowchart Diagram of While Loop Statement in Java


The flowchart for while loop in Java has shown in the below diagram.

Java while loop flowchart

Now consider the following code segment:

. . . . . 
. . . . .
int count = 0; // This variable has defined outside the loop and will update inside the loop.
while (count < 100) // Loop continuation condition that must always appear inside the parentheses. 
{
// Body of the loop.
   System.out.printIn("Hello Java"); // This statement executes while the condition is true.
   count++; // Counts the number of executions. // Increment count by 1.
}
. . . . .
. . . . .

From the above example, let’s understand how the loop works. The flowchart for this code segment has shown in the above diagram.

In this example code, the body of loop will execute 100 times for count = 0, 1, 2, 3, . . . . ., 99. Each time a statement “Hello Java” will print on the console.


When the count is equal to 100, the condition will be false and the loop will terminate. The control of execution transfers out of the loop.

count is a control variable that is used to control the number of executions. It increments by 1 after each loop. This kind of loop is called counter-controlled loop.

Example Program based on Java while loop statement


1. Let’s create a simple Java program to display the numbers from 1 to 5 by using while loop.

Program code 1:

package javaProgram;
public class WhileLoopEx {
public static void main(String[] args) 
{
 int i = 1; // Initialization.
 while(i <= 5)
 {
  System.out.println(i);
  i++; // Increment.
 }
}
}
Output:
      1
      2
      3
      4
      5

2. Let’s create a simple Java program to print a “Hello World!” four times on the console using a while loop.

Program code 2:

package javaProgram;
public class WhileLoopEx {
public static void main(String[] args) 
{
 int i = 1;
 while(i <= 4)
 {
  System.out.println("Hello World!");
  i++;
 }
 }
}
Output:
      Hello World!
      Hello World!
      Hello World!
      Hello World!

3. Let’s create a Java program to display numbers from 5 to 1 by using while loop statement.

Program code 3:

package javaProgram;
public class WhileLoopEx {
public static void main(String[] args) 
{
 int i = 5;
 while(i >= 1)
 {
   System.out.println(i);
   i--; // decrement.
 }
}
}
Output:
      5
      4
      3
      2
      1

4. Let’s consider an example program where we will add the number from 1 to 10 using while loop and display the sum on the console.

Program code 4:

package javaProgram;
public class Test {
public static void main(String[ ] args) 
{ 
   int sum = 0, i = 1;
   while (i <= 10) {
   sum = sum + i;
    i++;
 }
  System.out.println("sum is " + sum); // sum is 55
}}

In this example program, the variable i is initially set to 1 and the sum initially set to 0. When the conditional expression (i < 10) is true, the program adds i to the sum. Then, the variable i incremented to 2.

Again, the conditional expression evaluates to true. If it is true, the program adds i to sum. The variable is once again incremented to 3.

This process continues up to 10. Each time the program adds i to sum if the condition is true. After 10 iterations, the control of execution exits the loop. Therefore, the sum is 1 + 2 + 3 + … + 10 = 55.

While loop without Body Example Program


5. Let’s take another example program where the body of while loop will be empty. In this example, we will calculate the mid-value between i and j where i is equal to 10 and y is equal to 20.

Look at the following program source code to understand better.

Program code 5:

package javaProgram;
public class Test {
public static void main(String[] args) 
{ 
  int x = 10, y = 20;
  while (++x < --y); // No body in this loop.
  System.out.println("Mid value is " + x);
 }
}
Output:
       Mid value is 15

This example program finds the mid-value between x and y. Let’s understand how the while loop in the program works.

a. Initially, the value of x is set to 10 and y set to 20. These initially set values compare with one another. If the value of x is less than the value of y, the loop repeats.

b. Now, the value of x increments by 1, and the value of y decrements by 1. These new values then compare with one another. If the new value of x is still less than the new value of y, the loop once again repeats.

c. This process continues until the value of x is equal to or greater than the value of y.

d. When the value of x is equal to or greater than the value of y, the loop stops.

e. Upon exit from the loop, the variable x will hold a value that is midway between the original values of x and y.

As you can observe in the program, there is no need for a loop body. All the action happens within the conditional expression itself.


In this tutorial, you learned while loop statement in Java with example programs. Hope that you will have understood the basic concepts of while loop.

In the next tutorial, we will learn do while loop in Java that is another variant of while loop.
Thanks for reading!!!
Next ⇒ Do-while loop in Java

⇐ Prev Next ⇒