liveBook · Manning

Enhanced for statement

As explained in 100 Java Mistakes and How to Avoid Them

An enhanced for statement is Java syntax that traverses an Iterable or array by repeatedly obtaining elements for a loop body.

An enhanced for statement obtains an Iterable's iterator, checks hasNext(), assigns next() to the loop variable, runs the body, and repeats. Its predictable call order can conceal broken custom Iterator implementations. section 8.13

A contract violation hidden by for-each

An iterator that advances inside hasNext() may work for `for (int value : range(10))`, yet fail when a utility calls next() before hasNext(), or calls hasNext() repeatedly. Implement next() with its own bounds check and advance only after returning the current value. section 8.13

Avoid relying on enhanced-for call patterns:

  • Support next() before hasNext(), repeated hasNext() calls, and NoSuchElementException when exhausted. section 8.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the enhanced-for call sequence and contrasts it with iterator operations that the loop never performs.
Examples
Uses a generated integer range, a BufferedReader iterator, and corrected iterator implementations.
What it assumes
Assumes familiarity with Java collections, Iterable, Iterator, and exception behavior.
What you can do after
Diagnose iterator bugs and implement custom iterators that remain valid beyond enhanced-for traversal.
How it connects
Connects Iterable, Iterator, Collections.min, Collections.max, NoSuchElementException, IntStream, and BufferedReader.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.