beginnerFree

Loops

for, while, for-each - repeat with control

Loops

Loops let you repeat code. Choose the right loop for the job.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:23

The Big Picture

Loops repeat code until a condition changes.

  • for: count-based iteration with known bounds
  • while: condition-based, may not run at all
  • do-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.

  • break exits the loop, continue skips to next iteration
  • Labeled breaks exit outer loops: outer: for (...)
  • Collections: for-each uses an Iterator; arrays use indexed traversal
  • Infinite loops: while(true) or for(;;)

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 loops
  • Collections.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() or removeIf() 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
#java#fundamentals#loops