Three ways to repeat code in Java -- see them execute side by side
| Feature | while | do/while | for |
|---|---|---|---|
| Checks condition | Before body | After body | Before body |
| Minimum runs | 0 | 1 | 0 |
| Best for | Unknown iterations | At least once | Known count |
Set the slider to 0 and step through to see the difference, or press the button below for a quick demo.
for when you know how many times to loop. Use while when you're waiting for a condition. Use do/while when you need at least one iteration (rare in practice).
Color key: initialization | condition | body | update