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, the body of loop executes.
If the conditional expression does not satisfy, then the body of loop will not execute and the program will proceed to the next set of statements.
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.
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. // This statement counts the number of executions. On each execution, it increments the count by 1. count++; // 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.
Java While Loop Example Program
1. Let’s take a simple example program to display the numbers from 1 to 5 by using Java 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
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.
2. Let’s take another simple example 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; // initialization while(i <= 4) { System.out.println("Hello World!"); i++; } } }
Output: Hello World! Hello World! Hello World! Hello World!
3. Let’s take an example program to display numbers from 5 to 1 by using Java 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, 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 with Conditional Statements
We can also use a while loop in combination with conditional statements to perform more complex tasks. Let’s take an example of finding the sum of even numbers between 1 and 10.
Program code 5:
package javaProgram; 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 without Body Example
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 6:
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.
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. It allows us to handle more complex scenarios and work with multidimensional data structures effectively. For example:
Program code 7:
package javaProgram; 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.
Program code 8:
package javaProgram; 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++; } System.out.println(); // Move to the next row after printing all columns 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. 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
Q1: Can a while loop skip entirely if the condition is initially false?
A: Yes, if the condition of a while loop is false initially, the loop block will skip, and the program will proceed to the next set of statements.
Q2: Is it possible to nest multiple while loops in Java?
A: Absolutely, Java allows us to nest multiple while loops, enabling us to handle more complex scenarios efficiently.
Q3: Can we use the while loop to iterate over elements in an array?
A: 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.
Q4: What happens if the loop condition never becomes false?
A: 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.
In this tutorial, you learned while loop statement in Java with example programs. Hope that you will have understood the basic concept of while loop and how to use it in the program. In the next, we will learn about “do while loop” in Java that is another variant of while loop.
Thanks for reading!!!