Java While Loop (Simple Explanation + Live Examples)
β What is a While Loop?
The while loop in Java is a control flow statement that allows you to repeatedly execute a block of code as long as a condition remains true. Unlike the for
loop, the while loop is preferred when the number of iterations is not known beforehand β the loop continues running until the condition becomes false.
π§ Syntax of the While Loop
-
Condition: It must return
true
orfalse
. -
If the condition is
true
, the loop runs. -
If itβs
false
, the loop exits.
π― Example 1: Print Numbers from 1 to 5
Output:
π― Example 2: Input Until User Enters 0
Output:
β οΈ Infinite While Loop Example
This creates an infinite loop, which must be exited using a break
statement or other logic. Use with caution.
π Key Points
-
If the condition is
false
at the start, the loop does not run even once. -
Ensure the loop modifies the condition inside the block, or it may run forever.
-
Best used when waiting for a condition to be met (e.g., user input, flag update, file reading).
β When to Use a While Loop
-
You donβt know how many times the loop should run.
-
You want the loop to continue until something happens (like a user input).
-
You need pre-condition checking before entering the loop.