Introduction to While Loop
In Java, a while loop is a type of control flow statement that allows you to repeatedly execute a block of code as long as a specific condition remains true.
It is especially useful when you don’t know in advance how many times you need to repeat an action.
Syntax of While Loop
while (condition) {
// Code to execute repeatedly
}
- Condition is a Boolean expression that is checked before each iteration.
- If the condition is true, the code inside the loop runs.
- If the condition is false, the loop stops, and the program continues with the next statement after the loop.
Important Points About While Loop
Learn this points carefully:
- The condition is checked first before executing the loop body (pre-test loop).
- If the condition is false initially, the loop body may never execute.
- Sometimes, when you want to repeat a task, you don’t know in advance exactly how many times it should run. In such situations, a while loop is perfect because it keeps running as long as a condition is true.
Simple While Loop Example
public class WhileExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++; // Increment to eventually stop the loop
}
}
}
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Explanation of this code:
- We start with count = 1.
- The condition count <= 5 is checked before each iteration.
- The loop prints the current value of count and then increments it.
- Once count becomes 6, the condition becomes false, and the loop stops.
Other Examples of While Loop
Example 1: Sum of First N Natural Numbers
public class SumNumbersUnique {
public static void main(String[] args) {
int totalNumbers = 10;
int sum = 0;
int counter = 1;
while (counter <= totalNumbers) {
sum += counter; // Add current number to sum
counter++;
}
System.out.println("Total sum of numbers 1 to " + totalNumbers + " is: " + sum);
}
}
Output:
Total sum of numbers 1 to 10 is: 55
Example 2: User Input Until Exit
import java.util.Scanner;
public class UserCommandUnique {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
String command;
while (true) {
System.out.print("Type a command (or 'stop' to quit): ");
command = inputScanner.nextLine();
if (command.equalsIgnoreCase("stop")) {
break; // Stop the loop if user types "stop"
}
System.out.println("You typed: " + command);
}
System.out.println("Goodbye!");
inputScanner.close();
}
}
Output:
Type a command (or 'stop' to quit): Hello
You typed: Hello
Type a command (or 'stop' to quit): stop
Goodbye!
Example of Infinite While Loop
An infinite while loop is a loop that never stops on its own because its condition is always true.
public class EndlessLoopExample {
public static void main(String[] args) {
while (true) {
System.out.println("The loop is running endlessly!");
}
}
}
- If used carelessly, it can freeze your program, so always ensure there’s a way to break out if needed.
- The condition true never becomes false, so the loop keeps running indefinitely.
- Output of this program:
The loop is running endlessly!
The loop is running endlessly!
The loop is running endlessly!
...
Advantages of While Loop
The while loop is one of the most commonly used loops in Java, and it offers several benefits, such as:
- Flexibility:
- The while loop is perfect when you don’t know in advance how many times a task needs to be repeated.
- Simplicity:
- Its syntax is simple and easy to understand, which makes it beginner-friendly. You only need a condition and a loop body, so the logic is straightforward.
- Efficient for Certain Conditions:
- While loops are especially useful when handling conditions that may change unpredictably, such as waiting for a user to enter a correct value, and continuously reading data from a sensor or stream.
Exercise: Guess the Number Game
Create a simple number guessing game using a while loop.
- The program should randomly select a number between 1 and 20.
- The user should keep guessing numbers until they guess the correct number.
- After each wrong guess, the program should print whether the guess was too low or too high.
- When the user guesses correctly, print a congratulatory message and end the loop.
Requirements
- Use while loop to keep asking the user for input.
- Use Scanner to read user input.
- Use a condition in the while loop to continue until the correct number is guessed.
Sample Solution of This Exercise
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
int secretNumber = 7; // You can also use random number later
Scanner scanner = new Scanner(System.in);
int guess = 0;
System.out.println("Guess the secret number between 1 and 20:");
while (guess != secretNumber) {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else if (guess > secretNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the number.");
}
}
scanner.close();
}
}
- Practice using while loops for repetition.
- Learn conditional checks with if-else inside loops.
Also Learn Important Topics of Java
- What are the operators in Java Programming?
- What are Data Types in Java?
- What are the Variables in Java?
- Learn Java syntax.
- What is Java if else statements?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.