(Translated by https://www.hiragana.jp/)
Java while loop with Examples - GeeksforGeeks
Open In App

Java while loop with Examples

Last Updated : 13 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

while loop in Java

Syntax:

while (test_expression)
{
// statements

update_expression;
}

Note: If we do not provide the curly braces ‘{‘ and ‘}’ after while( condition ) then by default while statement will consider the immediate one statement to be inside its block.

while (test_expression)
// single statement in while only

Parts of Java While Loop

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. 

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? 

  1. Control falls into the while loop.
  2. The flow jumps to Condition
  3. Condition is tested. 
    • If Condition yields true, the flow goes into the Body.
    • If Condition yields false, the flow goes outside the loop
  4. The statements inside the body of the loop get executed.
  5. Updation takes place.
  6. Control flows back to Step 2.
  7. The while loop has ended and the flow has gone outside.

Flowchart For while loop (Control Flow): 

Flow chart while loop (for Control Flow

Examples of Java while loop

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++;
        }
    }
}


Output

Hello World
Hello World
Hello World
Hello World
Hello World

Complexity of the above method:  

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);
    }
}


Output

Summation: 55

Complexity of the above method

Time Complexity: O(1)
Auxiliary Space : O(1)

Video Referal for Java while Loop

 Related Articles: 

  1. Loops in Java
  2. Java For loop with Examples
  3. Java do-while loop with Examples
  4. Difference between for and while loop in C, C++, Java
  5. Difference between while and do-while loop in C, C++, Java


Previous Article
Next Article

Similar Reads

Difference between while and do-while loop in C, C++, Java
while loop: A 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. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int i =
2 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Syntax: do { // Loop Body Update_expression } // Condition check while (test_expression); Note: The
5 min read
While loop with Compile time constants
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. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
How to Avoid TLE While Coding in Java?
Avoiding Time Limit Exceeded(TLE) is one of the most important aspects that we need to take care of while doing competitive coding as well as while answering questions on DSA during a technical PI. In this context, one commonly asked question across all coding platforms is sorting or problems that involve sorting. The following code is something I
5 min read
ConcurrentModificationException while using Iterator in Java
ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException. Here we will be underst
3 min read
Java - Parameters Responsible for Difference in Outputs while Running on Local IDE vs Online IDE
The concept involved in the difference in output between running a Java program on a local IDE and an online IDE is the environment in which the program is being run. The specific version of Java, the settings and configurations of the IDE, and the instructions in the program can all affect the output of the program. To understand the differences i
4 min read
Remove an Entry using key from HashMap while Iterating over it
Given a HashMap and a key in Java, the task is to remove an entry from this HashMap using the key, while iterating over it. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: {1=Geeks, 3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 3 Output: {1=G, 2=e, 4=k, 5=s} Using Java 7 and before: Get the Hash
3 min read
Remove an Entry using value from HashMap while Iterating over it
Given a HashMap and a value in Java, the task is to remove an entry from this HashMap using the value, while iterating over it. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, value = "ForGeeks" Output: {1=Geeks, 3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, value = k Output: {1=G, 2=e, 3=e, 5=s} Using Java 7 and bef
3 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to PopUp DatePicker While Clicking on EditText in Android?
In android applications date pickers are used to pick the date from the calendars and display them within our text view. Many times we have to display this date picker dialog box by clicking on edit text and then we have to display that date within our edit text. In this article, we will take a look at How to Pop Up a Date Picker Dialog in the andr
4 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections. This loop also makes the code more readable and r
1 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i <= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
For-each loop in Java
Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Article Tags :
Practice Tags :