beginnerFree
Loops
for, while, for-each - repeat with control

Loops let you repeat code. Choose the right loop for the job.
Watch
The narrated version of this skribble — tap play for the full-size video.
0:00 / 1:23
Deep dive
The Big Picture
Loops repeat code until a condition changes.
for: count-based iteration with known boundswhile: condition-based, may not run at alldo-while: runs at least once, then checks condition- Enhanced for-each:
for (var item : list)
Loops are the backbone of data processing in Java.
How It Works
The JVM compiles loops to jump instructions. Hot loops get JIT-compiled to native code with optimizations.
breakexits the loop,continueskips to next iteration- Labeled breaks exit outer loops:
outer: for (...) - Collections: for-each uses an
Iterator; arrays use indexed traversal - Infinite loops:
while(true)orfor(;;)
In the Java Landscape
Modern Java offers functional alternatives to loops.
- Streams:
list.stream().filter(...).map(...) forEach():list.forEach(item -> process(item))IntStream.range(0, n)replaces index-based for loopsCollections.nCopies()for repeated values- Use loops for simple iteration, streams for transforms
Pitfalls and Best Practices
- Off-by-one: use < not <= for zero-based arrays
- Don't modify a collection while iterating with for-each
- Use
Iterator.remove()orremoveIf()instead - Avoid infinite loops - ensure termination condition changes
- Prefer for-each over indexed for when index isn't needed
- Extract loop body into a method if longer than 10 lines



