A while loop in Java is an entry control flow statement that allows a block of code to be executed repeatedly based on the specified Boolean condition. This is one of the simplest looping constructs.
When we don’t know the number of iterations beforehand, we mainly use the while loop. For example, suppose you are trying to guess a password on your phone. You don’t know how many attempts it will take to get it right — maybe 1 try, maybe 5 tries.
So, the logic goes like this:
- “While the password is incorrect, keep asking the user to enter it again.”
Once the password is correct, the loop stops.
Syntax of While Loop in Java
The syntax of a while loop is very simple and straightforward:
while (condition) {
// body of the loop
// code to be executed repeatedly
}In the above syntax,
- while: This is a keyword in Java that starts the loop declaration. It tells the compiler that a loop will follow.
- condition: This is a Boolean expression. It must evaluate to either true or false.
- If the condition evaluates to true, the code inside the loop body executes.
- If the condition evaluates to false, the loop terminates, and the program control continues to the execution of the next statement after the loop.
- { }: This is curly braces enclose the body of the loop, which contains the set of statements to be executed on each iteration as long as the condition remains true.
How Does a While Loop Work? (The Flowchart)
Here’s how the while loop works step by step:
- The loop first evaluates the Boolean condition.
- If the condition is true, the code inside the loop body is executed.
- After the body executes, the condition is evaluated again.
- If it’s still true, the loop body runs again.
- This process repeats until the condition becomes false.
- When the condition becomes false, the loop stops.
Look at the below flowchart diagram.

Basic Example of While Loop in Java
Let’s look at some simple examples to get you started.
Example 1: Printing Numbers from 1 to 5
int i = 1; // Initialize a counter
// This condition runs until i is less than or equal to 5.
while (i <= 5) {
System.out.println("Count is: " + i);
i++; // Increment the counter.
}Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5In this example,
- Initially, the variable counter i = 1.
- The loop runs while i <= 5.
- Each iteration prints the value of i and then increments it by 1.
- When the counter i becomes 6, the condition is false, and the loop stops.
Example 2: Sum of Numbers Using While Loop
Let’s write a Java program to calculate the sum of first 10 natural numbers using a while loop.
public class Sum {
public static void main(String[] args) {
int i = 1, sum = 0;
while (i <= 10) {
sum += i;
i++;
}
System.out.println("Sum = " + sum);
}
}Output:
Sum = 55In this example, we have declared two integer variables i and sum and initialized them with 1 and 0, respectively. The first variable i acts as counter starting from 1. Another variable sum stores the running total (starts at 0).
The while loop executes the code inside the loop body as long as the counter variable i is less than or equal to 10. That means the loop will execute for i = 1 to i = 10.
When i becomes 11, the condition (i <= 10) becomes false, and the loop stops. After the loop ends, the line System.out.println(“Sum = ” + sum); prints the final value of sum.
Look at the below table and what happens in each iteration:
| Iteration | i | sum (before) | sum = sum + i | sum (after) |
|---|---|---|---|---|
| 1 | 1 | 0 | 0 + 1 | 1 |
| 2 | 2 | 1 | 1 + 2 | 3 |
| 3 | 3 | 3 | 3 + 3 | 6 |
| 4 | 4 | 6 | 6 + 4 | 10 |
| 5 | 5 | 10 | 10 + 5 | 15 |
| 6 | 6 | 15 | 15 + 6 | 21 |
| 7 | 7 | 21 | 21 + 7 | 28 |
| 8 | 8 | 28 | 28 + 8 | 36 |
| 9 | 9 | 36 | 36 + 9 | 45 |
| 10 | 10 | 45 | 45 + 10 | 55 |
The program calculates the sum of numbers from 1 to 10 using a while loop. Each time through the loop, it adds the current number (i) to sum. The final result, 55, is displayed after the loop completes.
This is a classic example of using a while loop when you need to repeat a calculation until a condition (here, i <= 10) becomes false.
Example 3: Reverse a Number using While Loop
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}Output:
Reversed Number: 54321Example 4: Palindrome Check Using While Loop
public class PalindromeCheck {
public static void main(String[] args) {
int num = 1221;
int original = num;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
if (original == reversed)
System.out.println("Palindrome Number");
else
System.out.println("Not a Palindrome");
}
}Output:
Palindrome NumberNested While Loop in Java
When you put one while loop inside another while loop, it is called nested while loop in Java. It’s just like having a loop within a loop — the inner loop executes completely for each iteration of the outer loop.
The general syntax of the nested while loop in Java is as:
// Outer loop
while (condition1) {
// statements
// Inner loop
while (condition2) {
// inner loop statements
}
// other statements
}In the above syntax of nested while loop,
- Outer loop executes first and controls how many times the inner loop executes in total.
- Inner loop executes multiple times for each iteration of the outer loop.
- The inner loop must have its own condition and inner loop counter variable. They usually reset for every new outer loop iteration.
Examples of Nested While Loop in Java
Let’s take some important examples based on the nested while loop in Java that you should must practice for interviews.
Example 1: Print a Simple Pattern
Let’s print a 3×3 grid of stars (★) using nested while loops.
public class NestedWhileExample1 {
public static void main(String[] args) {
int i = 1; // Outer loop counter
// Outer loop
while (i <= 3) {
int j = 1; // Inner loop counter
// Inner loop
while (j <= 3) {
System.out.print("* ");
j++;
}
System.out.println(); // Move to next line after inner loop finishes
i++;
}
}
}Output:
* * *
* * *
* * *In this example,
- The outer loop (controlled by i) runs 3 times. Each represents one row.
- The inner loop (controlled by j) runs 3 times per outer loop iteration and prints 3 stars in one row.
- Once the inner loop completes, the outer loop moves to the next line and repeats.
Example 2: Printing Numbers in a Pattern
Let’s print a matrix of numbers using nested while loops.
public class NestedWhileExample2 {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
System.out.print(j + " ");
j++;
}
System.out.println();
i++;
}
}
}Output:
1 2 3
1 2 3
1 2 3Advanced Example 3: Multiplication Table
Now let’s write a Java program to print a multiplication table from 1 to 5 using nested while loop.
public class NestedWhileExample3 {
public static void main(String[] args) {
int i = 1; // Outer loop
while (i <= 5) {
int j = 1; // Inner loop
while (j <= 10) {
System.out.print(i * j + "\t");
j++;
}
System.out.println(); // Move to next line
i++;
}
}
}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 50In this example,
- The outer loop controls the multiplier (i = 1 to 5).
- The inner loop runs from j = 1 to 10, printing each product (i × j).
- After completing one row, the inner loop resets, and the outer loop increments i.
Advanced Example 4: Triangle Number Pattern
public class NestedWhileExample4 {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print(j + " ");
j++;
}
System.out.println();
i++;
}
}
}Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5In this example,
- The outer loop (i) determines the number of rows (1 to 5).
- The inner loop (j) prints numbers from 1 up to i for each row.
- Each new row increases the number of printed elements.
Advanced Example 5: Pattern of Stars
Let’s write a Java program to display the pattern of stars using nested while loops.
public class NestedWhileExample5 {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
}
}Output:
*
* *
* * *
* * * *
* * * * *Thus, a nested while loop runs the inner loop completely for each iteration of the outer loop, which is perfect for patterns, tables, or multi-dimensional structures.
Infinite While Loop in Java
An infinite while loop in Java is a loop that never ends. It keeps executing the same block of code forever because the condition always remains true. If that condition never becomes false, the loop will never stop.
The basic syntax of infinite while loop is as:
while (true) {
// statements
}In this syntax, the condition true is a Boolean literal that is always true, so the loop never exits on its own. Since the condition inside the while loop (true) never becomes false, the program keeps executing the statements inside the loop without stopping.
Example 1: Basic Infinite While Loop
public class InfiniteWhileExample {
public static void main(String[] args) {
while (true) {
System.out.println("Infinite loop runs forever!");
}
}
}Output:
Infinite loop runs forever!
Infinite loop runs forever!
Infinite loop runs forever!
...In this example, the message will keep printing continuously until you manually stop the program.
How to Stop It?
You can manually stop an infinite loop by:
- Pressing Ctrl + C in the terminal (if running in command line), or
- Clicking the Stop/Terminate button in your IDE (like Eclipse, IntelliJ, or VS Code).
Example 3: Using Infinite While Loop in Real-Life Scenarios
Infinite loops are sometimes used intentionally in real-world applications, but you must use with control conditions inside (like break statement).
import java.util.Scanner;
public class MenuExample {
public static void main(String[] args) {
// Create an object of Scanner class to get input from keyboard.
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("\n=== MENU ===");
System.out.println("1. Say Hello");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
if (choice == 1) {
System.out.println("Hello, User!");
} else if (choice == 2) {
System.out.println("Exiting program...");
break; // Stop the loop
} else {
System.out.println("Invalid choice! Try again.");
}
}
sc.close();
}
}Output:
=== MENU ===
1. Say Hello
2. Exit
Enter your choice: 1
Hello, User!
=== MENU ===
1. Say Hello
2. Exit
Enter your choice: 2
Exiting program...In this example, the loop is infinite because the condition inside while statement remains true. But it contains a break statement that stops the loop when the user chooses 2 (Exit). This type of infinite loop is common in menu-driven programs, servers, or event listeners.
FAQs About While Loop in Java
1. What is the difference between while and for loop in Java?
Answer: for is used when you know the number of iterations; while loop is used when you don’t know the number of iterations or depends on a condition.
2. Can we use break and continue inside a while loop?
Answer: Yes, you can use break and continue statements inside the while loop. Break exits the loop immediately, and continue skips the current iteration.
3. Can a while loop run zero times?
Answer: Yes, if the condition is false initially, the loop body won’t execute even once.
4. Is it possible to use multiple conditions in while loop?
Answer: Yes, you use logical operators to combine multiple conditions in the while loop. For example:
while (a < 10 && b > 5) { … }
5. What happens if the condition in a while loop is always true?
Answer: If the condition in a while loop is always true, it creates an infinite loop.
Test Your Knowledge
1. What will be the output of the following code?
int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}a) 0 1 2
b) 1 2 3
c) Infinite loop
d) 0 1 2 3
Answer: a) 0 1 2
2. Which of the following is true for while loop?
a) Condition is checked after execution
b) Executes at least once
c) Condition is checked before execution
d) None of the above
Answer: c) Condition is checked before execution
Conclusion
The while loop in Java is a fundamental construct for repeating tasks based on conditions. It’s most useful when you don’t know beforehand how many times you need to repeat a block of code. We hope that you learned about the basic syntax of while loop in Java and practiced all example programs based on it.





