while Loop in Java
A while loop repeats its body for as long as its condition stays true, checking that condition before every iteration — including the very first one, so the body might not run even once if the condition starts out false. It's the natural choice whenever the number of iterations isn't known ahead of time and instead depends on some changing state, like reading input until a sentinel value appears.
Since nothing about a while loop's syntax updates its own condition automatically, something inside the body has to change a variable the condition depends on, or the loop runs forever. An infinite loop is almost always a while loop whose body forgot to update the thing it's checking.
The syntax
while (condition) { body } repeats the body for as long as condition stays true.
Condition checked first
Evaluated before every iteration, including the first, so the body can end up running zero times.
Nothing updates automatically
Unlike a for loop's built-in update step, a while loop relies entirely on its body to eventually make the condition false.
Best suited to unknown iteration counts
Used when how many times to loop depends on changing state, not a fixed number decided in advance.
The classic infinite-loop bug
Forgetting to update the variable the condition depends on inside the body means the condition never becomes false.
public class WhileLoopDemo { public static void main(String[] args) { int count = 3; while (count > 0) { System.out.println("Countdown: " + count); count--; } System.out.println("Liftoff!"); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.