• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Many programming tasks require executing the same block of code repeatedly — processing each element of an array, reading lines from a file, or retrying an operation until it succeeds. Without loops, every repetition would require manual code duplication, leading to bloated, error-prone programs.

Core Idea

Java provides three loop constructs: for (when the number of iterations is known), while (when iteration continues as long as a condition is true), and do-while (same as while but guarantees at least one execution). The enhanced for-each loop simplifies iteration over arrays and collections.

How It Works

A loop consists of an initialization, a termination condition, an update expression (for for loops), and a body. The JVM evaluates the condition before (or after, for do-while) each iteration. If true, the body executes; if false, execution jumps past the loop. The for-each loop uses an iterator under the hood for collections.

Visual Explanation

java_loops Init Initialization int i = 0 Cond Condition Check i < 5 Init->Cond Body Loop Body Execute statements Cond->Body true Exit Exit Loop Continue after Cond->Exit false Update Update i++ Body->Update Update->Cond

Semantic Network

semantic_loops THIS Loops CTRL Control Flow THIS--CTRL built from JUMP Jump Statements THIS--JUMP builds into ARR Arrays THIS--ARR builds into COLL Collections THIS--COLL builds into

Key Properties

  • For-each syntax: for (Type var : iterable) — cleaner, no index variable
  • While: Zero or more iterations (condition checked first)
  • Do-while: One or more iterations (condition checked after first run)
  • Nested loops: Loops inside loops for multi-dimensional traversal

Connections

Edge Cases & Gotchas

  • Infinite loops: while(true) or for(;;) without break conditions
  • Off-by-one errors: Using <= instead of < in loop conditions
  • Concurrent modification: Modifying a collection while iterating with for-each throws ConcurrentModificationException
  • Performance: Enhanced for-each on arrays is identical to index-based loops after compilation