Java while Loop

Last Updated : 16 Jan, 2026

Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed.

Let's go through a simple example of a Java while loop:

Java
public class WhileLoop {
    public static void main(String[] args) {
      
      // Initialize the counter variable
      int c = 1; 

        // While loop to print numbers from 1 to 5
        while (c <= 5) {
          
          System.out.println(c); 
            
          // Increment the counter
          c++; 
        }
    }
}

Output
1
2
3
4
5

Explanation: In this example, it prints the numbers from 1 to 5 by repeatedly executing the loop as long as the counter variable "c" is less than or equal to 5.

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.

Execution of While Loop in Java

Now, let's understand the execution flow of while loop with the below diagram:

Java While Loop
  1. Control enters the while loop.
  2. The condition is tested.
  3. If true, execute the body of the loop.
  4. If false, exit the loop.
  5. After executing the body, update the loop variable.
  6. Repeat from step-2 until the condition is false.

Examples of Java while loop

Below are the examples of Java while loop that demonstrates repeating actions and performing calculations.

Example: Repeating a Message with while loop

Java
class whileLoop {
    public static void main(String args[])
    {
        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

Explanation: In the above example, the while loop runs until "i" is less than 6 and prints "Hello World" 5 times.

Example: Calculating the Sum of Numbers from 1 to 10 with Java while Loop

Java
class whileLoop {
    public static void main(String args[])
    {
        int i = 1, s = 0;

        // loop continues until i becomes greater than 10
        while (i <= 10) {
            
            // add the current value of i to s
            s = s + i;

            // increment i for the next iteration
            i++;
        }
        System.out.println("Summation: " + s);
    }
}
Try it on GfG Practice
redirect icon

Output
Summation: 55

Explanation: This program finds the summation of numbers from 1 to 10. 

Comment