While Loop in Java
The while loop in Java is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. It is known as a pre-test loop because the condition is checked before the code block executes. If the condition is false from the start, the loop body will not execute at all.
How It Works
The condition is evaluated first.
If the condition is true, the statements inside the loop body are executed.
After execution, the control goes back to re-check the condition.
The process repeats until the condition becomes false.
Once the condition is false, the loop terminates, and the program continues with the next statement after the loop.
Syntax
while (condition) {
// code to be executed
// update expression (e.g., i++)
}Explanation of syntax:
condition - A boolean expression that decides whether the loop continues.
code to be executed - The statements inside the loop that run repeatedly while the condition is true.
Get Quipoin’s stories in your inbox
Join Medium for free to get updates from this writer.
update expression - Changes the loop variable (e.g., i++), so the condition can eventually become false and stop the loop.
Example: Printing Numbers 1 to 5
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1; // initialization
while (i <= 5) { // condition
System.out.println(i); // loop body
i++; // update expression
}
}
}Output
1
2
3
4
5In this example:
The loop starts with i = 1.
As long as i <= 5, the code inside the loop executes.
After each iteration, i increases by 1 (i++).
When i becomes 6, the condition is false, and the loop stops.
Key Points
The while loop executes statements only if the condition is true.
It is also known as an entry-controlled loop, since the condition is checked before execution.
If the condition is initially false, the loop body will never run.
Commonly used when the number of iterations is not known in advance and depends on a condition.
When to Use a While Loop
When you want to keep executing code until a certain condition is met.
When the number of iterations is not fixed beforehand.
Useful for tasks like reading input until the user chooses to exit, checking for a particular value, or waiting for a condition to change during runtime.
Java in 30 Days YouTube Playlist — Step-by-step video tutorials.
Java Exercises — Practice coding problems to sharpen your skills.
Java Interview Questions — Prepare for technical interviews confidently.




