The while loop in Java is one of the most fundamental loop statements that repeatedly executes a statement or series of statements as long as the specified conditional expression evaluates to true.
In other words, a while loop continues to execute the body of the loop as long as the loop condition holds. Each repetition of the body of loop is called iteration.
The while loop is the simplest of all the looping structures in Java. It is an entry-controlled loop statement in which the test condition evaluates before the execution of the loop body. If the specified condition is true, the body of loop executes.
If the condition does not satisfy, the loop body will not execute, and control passes to the next statement after the loop.
Syntax of While Loop in Java
A while loop is one of the most fundamental looping statements in Java. It executes a block of code repeatedly while the test condition is true. The general syntax for using the while loop in Java:
Initialization;
while(test condition)
{
// Loop body
Statement(s);
Increment/Decrement;
}In the above syntax:
- while is a keyword in Java.
- The test condition must be a boolean expression, which evaluates to either true or false.
- This condition is evaluated before the execution of the loop body, making it an entry-controlled loop.
- The boolean expression controls the execution of the loop body.
How Does a While Loop Work in Java?
First, the test condition is evaluated. If the test condition is true, the body of loop (statements) executes. After the execution of the loop body, the test condition is evaluated again.
If the specified condition is still true, the loop body executes once again. This process of repeated execution of loop body continues until the condition finally becomes false. Once the condition is false, the loop terminates and the control then passes to the next statement after the loop.
Each execution of the loop body is referred to as an iteration (or repetition). The part of the loop that contains statements to be executed repeatedly is called the loop body. The loop body may contain one or more statements.
Curly braces {} are optional if there is only one statement. It is 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.
Example:
while (i < 5) i++; // valid but not recommended.
Recommended:
while (i < 5) {
i++;
}Flowchart Diagram of While Loop Statement in Java
The flowchart diagram of the while loop in Java is shown below.
Working of While Loop with Example
Now consider the following example code.
public class WhileLoopExample {
public static void main(String[] args) {
// This is a control variable, which is defined outside the loop and will update inside the loop.
int count = 0; // Control variable
while (count < 10) { // Loop will run until count is less than 10.
// Body of the loop.
// This statement executes until the specified condition is true.
System.out.println("Hello Java");
// This statement counts the number of executions. On each execution, it increments the count by 1.
count++; // Increment count by 1
}
}
}In this example:
- We have defined a variable named count and assigned the value 0 to it.
- This variable is called a control variable because it controls the number of loop iterations.
- Therefore, this type of loop is known as a counter-controlled loop, where the number of iterations is determined by a counter variable.
- The counter variable is incremented by 1 during each iteration.
- Now the loop starts with variable count = 0.
- The condition count < 10 is checked before each iteration. If the condition evaluates to true, the loop body executes.
- Since the condition is true for the values of count from 0 to 9, the loop body executes 10 times.
- During each iteration, the statement “Hello Java” is printed on the console.
- As a result, the message “Hello Java” is printed 10 times on separate lines.
- When the value of count becomes 10, the condition count < 10 evaluates to false, and the loop terminates. Control then transfers to the next statement after the loop.
Java While Loop Example Program
Let’s take a simple example program to display the numbers from 1 to 5 in Java by using while loop.
Example 1: Print Numbers from 1 to 5
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
In this example, the initialization of while loop starts from i = 1. The while loop continues to print the value of “i” as long as “i” is less than or equal to 5. In each iteration, the value of variable i is incremented by 1 until the condition becomes false.
Let’s consider another example program to print a “Hello World!” four times on the console using a while loop.
Example 2: Print Hello World 4 times
public class WhileLoopEx {
public static void main(String[] args)
{
int i = 1; // Initialization
while(i <= 4)
{
System.out.println("Hello World!");
i++;
}
}
}
Output:
Hello World! Hello World! Hello World! Hello World!
Let’s take an example program to display numbers from 5 to 1 in Java by using while loop statement.
Example 3: Print Numbers from 5 to 1
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
Let us take an example program where we will add the number from 1 to 10 using while loop and display the sum on the console.
Example 4: Calculate the Sum of Numbers from 1 to 10
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 = " + sum);
}
}Output:
Sum = 55
In this example, 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” is incremented to 2.
Again, the conditional expression is checked to evaluate to true. If the condition is true, the program adds i to the sum. The variable is once again incremented to 3.
This process continues up to 10. Each time the program adds i to the sum if the condition is true. After 10 iterations, the control of execution exits the loop and prints the sum of numbers from 1 to 10. Hence, the sum is 1 + 2 + 3 + … + 10 = 55.
While Loop with Conditional Statements
We can also use a while loop in combination with conditional statements to perform more complex tasks in Java. Let’s take an example of finding the sum of even numbers between 1 and 10 using while loop statement in combination with conditional statements.
Example 5: Calculate the Sum of Even Numbers between 1 to 10
public class WhileLoopEx {
public static void main(String[] args)
{
int num = 1;
int sum = 0;
while (num <= 10) {
if (num % 2 == 0) {
sum += num;
}
num++;
}
System.out.println("Sum of even numbers between 1 and 10: " +sum);
}
}Output:
Sum of even numbers between 1 and 10: 30
While Loop Statement Without Body
Let’s take an example program where the body of while loop will be empty. We will calculate the mid-value between x and y, where x is equal to 10 and y is equal to 20.
Example 6: Calculate Mid-Value between 10 to 20
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.
- Initially, the value of x is set to 10 and y set to 20. The initially set values compare with one another. If the value of x is less than the value of y, the loop repeats.
- 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.
- This process continues until the value of x is equal to or greater than the value of y.
- When the value of x is equal to or greater than the value of y, the loop stops.
- 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.
Nested While Loops in Java
In Java, it is also possible to have nested while loops. When we place a while loop inside another loop, it is called nested while loops in Java. It allows us to handle more complex scenarios and work with multidimensional data structures effectively.
Example 7: Nested While Loop
public class NestedWhileLoopsExample {
public static void main(String[] args)
{
// Initialization of outer while loop,
int outerLoop = 1;
// Outer while loop
while (outerLoop <= 3)
{
// Initialization of inner while loop.
int innerLoop = 1;
// Inner while loop
while (innerLoop <= 3)
{
System.out.println("Outer loop iteration: " + outerLoop + ", Inner loop iteration: " + innerLoop);
innerLoop++;
} // inner while loop ends here.
outerLoop++;
} // outer while loop ends here.
}
}
Output:
Outer loop iteration: 1, Inner loop iteration: 1 Outer loop iteration: 1, Inner loop iteration: 2 Outer loop iteration: 1, Inner loop iteration: 3 Outer loop iteration: 2, Inner loop iteration: 1 Outer loop iteration: 2, Inner loop iteration: 2 Outer loop iteration: 2, Inner loop iteration: 3 Outer loop iteration: 3, Inner loop iteration: 1 Outer loop iteration: 3, Inner loop iteration: 2 Outer loop iteration: 3, Inner loop iteration: 3
In this example:
- We have created two while loops: the outer while loop and the inner while loop.
- The outer loop executes three times. On each iteration, the inner loop executes three times.
- As a result, we get all possible combinations of outer and inner loop iterations displayed on the console.
We commonly use Java nested while loops when dealing with two-dimensional arrays or complex data structures that need nested iterations. Keep in mind that nesting too many while loops can lead to less efficient code. So, use them judiciously.
Let us take another simple example based on the nested while loops in Java.
Example 8:
public class MultiplicationTable {
public static void main(String[] args)
{
int row = 1;
// Outer while loop for rows
while (row <= 10)
{
int column = 1;
// Inner while loop for columns
while (column <= 10)
{
int result = row * column;
System.out.print(result + "\t");
column++;
}
// Move to the next row after printing all columns.
System.out.println();
row++;
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
In this example code:
- We have used nested while loops to create a multiplication table from 1 to 10.
- Each row represents the multiplication of a number from 1 to 10.
- Each column shows multiplication with numbers from 1 to 10.
- The outer while loop iterates over the rows, and the inner while loop iterates over the columns for each row.
- We have displayed the result of multiplying the row number by the column number in a tab-separated format, which will create a multiplication table.
FAQs on While Loops
1. Can a while loop skip entirely if the condition is initially false?
Answer: Yes, if the condition of a while loop is false initially, the loop block will be skipped, and the program will proceed to the next set of statements.
2. Is it possible to nest multiple while loops in Java?
Answer: Absolutely, Java allows us to nest multiple while loops, enabling us to handle more complex scenarios efficiently.
3. Can we use the while loop to iterate over elements in an array?
Answer: Yes, we can use while loop for this purpose, but for loop is more suited when you already know the number of elements in the array.
4. What happens if the loop condition never becomes false?
Answer: An infinite loop occurs if the loop condition never becomes false. This can lead to the program running indefinitely and may result in a program crash.





