Java while loop with Examples

23 Jun, 2022
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number of iterations is not fixed, it is recommended to use the while loop.
Syntax:
while (test_expression)
{
   // statements
 
  update_expression;
}
The various parts of the While loop are: 
1. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop. 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Example: 
i <= 10
2. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. 
Example: 
i++;
How Does a While loop execute? 
Control falls into the while loop.The flow jumps to ConditionCondition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.Updation takes place.Control flows back to Step 2.The while loop has ended and the flow has gone outside.
Control falls into the while loop.
The flow jumps to Condition
Condition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone outside.
Flowchart For while loop (Control Flow):  
Example 1: This program will try to print “Hello World” 5 times. 
Java
// Java program to illustrate while loop. class whileLoopDemo {    public static void main(String args[])    {        // initialization expression        int i = 1;         // test expression        while (i < 6) {            System.out.println("Hello World");             // update expression            i++;        }    }}
  
Hello World
Hello World
Hello World
Hello World
Hello World
Time Complexity: O(1)
Auxiliary Space : O(1) 
Dry-Running Example 1: The program will execute in the following manner. 
 
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
  3.a) "Hello World" gets printed 1st time.
  3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
  4.a) "Hello World" gets printed 2nd time.
  4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
  5.a) "Hello World" gets printed 3rd time
  5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
  6.a) "Hello World" gets printed 4th time
  6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
  7.a) "Hello World" gets printed 5th time
  7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.
 
Example 2: This program will find the summation of numbers from 1 to 10. 
Java
// Java program to illustrate while loop class whileLoopDemo {    public static void main(String args[])    {        int x = 1, sum = 0;         // Exit when x becomes greater than 4        while (x <= 10) {            // summing up x            sum = sum + x;             // Increment the value of x for            // next iteration            x++;        }        System.out.println("Summation: " + sum);    }}
Summation: 55
Time Complexity: O(1)
Auxiliary Space : O(1) 
3. While Loop in Java (Core Java)| GeeksforGeeks - YouTubeGeeksforGeeks529K subscribers3. While Loop in Java (Core Java)| GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 16:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xBJ44A1FCTE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Related Articles: 
 
Loops in JavaJava For loop with ExamplesJava do-while loop with ExamplesDifference between for and while loop in C, C++, JavaDifference between while and do-while loop in C, C++, Java
Loops in Java
Java For loop with Examples
Java do-while loop with Examples
Difference between for and while loop in C, C++, Java
Difference between while and do-while loop in C, C++, Java
 
nishkarshgandhi
rishavnitro
tarunkanade
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++