Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A for loop in Java is a control flow statement that repeatedly executes a block of code based on a boolean condition. It consolidates loop initialization, condition evaluation, and iteration updates into a single line of syntax. Java supports two primary variations: the traditional for loop and the enhanced for loop (often referred to as the for-each loop).

Traditional for Loop

The traditional for loop header consists of three distinct sections separated by semicolons, followed by the loop body.
for (initialization; condition; update) {
    // loop body
}
  • Initialization: Executed exactly once before the loop begins. This section must be either a local variable declaration or a comma-separated list of statement expressions (e.g., assignments, increments/decrements, object creations, or method invocations). Arbitrary expressions (like a + b or x == 5) are invalid and will cause a compilation error. Variables declared here are block-scoped exclusively to the loop.
  • Condition: A boolean expression evaluated before every iteration. If it evaluates to true, the loop body executes. If it evaluates to false, the loop terminates, and the execution pointer jumps to the first statement following the loop block.
  • Update: A comma-separated list of statement expressions invoked immediately after the loop body completes its execution for that iteration.
Execution Flow:
  1. The initialization section executes.
  2. The condition expression is evaluated.
  3. If false, the loop terminates. If true, the loop body executes.
  4. The update statement expression(s) execute.
  5. Control returns to step 2.
Omitted Sections: All three sections in the traditional for loop header are optional. Omitting all of them results in an infinite loop, equivalent to while (true).
for (;;) {
    // infinite loop body
}

Enhanced for Loop (For-Each)

Introduced in Java 5, the enhanced for loop abstracts away the underlying index or iterator mechanics. It is strictly used for traversing arrays or objects that implement the java.lang.Iterable interface (such as the Java Collections Framework).
for (Type variable : iterable) {
    // loop body
}
  • Type: The data type of the elements contained within the array or collection.
  • Variable: A local, block-scoped variable that holds the value of the current element being processed. A new local variable is created and initialized for each iteration. It acts as a standard local variable and can be reassigned by the developer within the loop body unless explicitly declared final. If the developer chooses not to modify it, the variable is considered “effectively final” and can be safely captured inside lambdas or anonymous inner classes.
  • Iterable: The target array or Iterable object being traversed.
Limitations of the Enhanced for Loop:
  • No Index Access: The enhanced for loop does not provide access to the current iteration index. If the loop logic requires the index (e.g., for conditional logic based on position or modifying the array in place), a traditional for loop must be used.
  • No Safe Element Removal via Iterator: Because the underlying Iterator is abstracted away, developers cannot call Iterator.remove(). Attempting to remove elements directly from a collection during an enhanced for loop iteration will throw a ConcurrentModificationException if the collection uses a fail-fast iterator (such as ArrayList or HashMap). This exception is a property of the specific iterator implementation, not the loop itself; concurrent collections utilizing weakly consistent iterators (such as CopyOnWriteArrayList or ConcurrentLinkedQueue) will not throw this exception if modified during iteration.

Loop Control Statements

The execution flow of both for loop variants can be explicitly altered using control transfer statements:
  • break: Immediately terminates the innermost loop in which it resides. Control passes to the statement immediately following the loop block.
  • continue: Bypasses the remaining statements in the loop body for the current iteration.
    • In a traditional for loop, control jumps directly to the update statement expression.
    • In an enhanced for loop over an array (which compiles down to a traditional loop), control jumps to the update expression of the hidden index variable.
    • In an enhanced for loop over an Iterable, control jumps to the underlying Iterator.hasNext() condition evaluation.
  • Labeled break / continue: Java allows loops to be prefixed with a label (e.g., outerLoop:). Using break labelName; or continue labelName; allows developers to control the flow of nested loops from within an inner loop.
Master Java with Deep Grasping Methodology!Learn More