Java Tutorial: Loops
for, while, do-while, enhanced for-each, break, continue, and labeled loops — control repetition in Java.
Repetition is the engine of computing
Loops are what turn a 10-line program into one that processes a million records. Java has four loop types — each with its ideal use case.
What you'll learn in this Java loops tutorial
This interactive Java tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- for loop — counted repetition — The classic `for` loop: initialise, condition, update:
- for-each — iterate over arrays — The enhanced for-each loop is cleaner when you don't need the index:
- while — loop until condition changes — `while` loops while the condition is true. Use it when you don't know upfront how many iterations you need.
- do-while — run at least once — `do-while` runs the body FIRST, then checks the condition. Guaranteed to run at least once.
- break — exit early — `break` immediately exits the loop. Once you find what you're looking for, stop — no point continuing.
- continue — skip this iteration — `continue` skips the rest of the current iteration and goes to the next one.
- Nested loops — Loops inside loops. Inner loop runs completely for every outer iteration.
- FizzBuzz — the classic interview test — Almost every programming interview includes this problem.
Java Loops concepts covered
- Repetition is the engine of computing