1. Introduction
The for loop is Java's primary construct for repeating a block of code a known or countable number of times. Java offers two forms: the classic three-part for loop, which gives explicit control over initialization, condition, and update, and the enhanced for-each loop, which simplifies iteration over arrays and collections.
Cricket analogy: The classic for loop is like a scorer manually counting each of the 50 overs one by one with full control, while the for-each loop is like simply reading a printed scorecard of all batsmen without tracking each one's index.
Choosing between the two depends on whether index access is needed: the classic for loop is preferred when the loop counter itself matters (e.g., for reverse iteration or skipping elements), while for-each is preferred for simple, readable traversal of an entire collection.
Cricket analogy: Choosing the classic for loop for reverse iteration is like reviewing the last five overs of an innings backward to analyze a collapse, while for-each suits simply reading through the full scorecard in order.
2. Syntax
// Classic three-part for loop
for (initialization; condition; update) {
// loop body
}// Enhanced for-each loop
for (Type element : collectionOrArray) {
// loop body using element
}3. Explanation
In the classic for loop, initialization runs once before the loop starts, the condition is checked before each iteration (loop stops when it becomes false), and the update expression runs after each iteration. All three parts are optional, and omitting all of them (for (;;)) creates an infinite loop.
Cricket analogy: In the classic for loop, the toss happens once (initialization), the umpire checks weather conditions before every over (condition), and the scoreboard updates after each over (update) — omitting all three creates an endless match, like for(;;).
The for-each loop, introduced in Java 5, works with any array or any object implementing the Iterable interface (such as ArrayList, HashSet, etc.). It hides the iterator/index mechanics, making code more concise, but it does not expose the current index and the element variable is effectively read-only for primitives in terms of affecting the underlying collection.
Cricket analogy: The for-each loop, like a TV highlights reel introduced for modern broadcasts, simply plays through every wicket in an innings (any Iterable collection) without exposing which specific ball number triggered it, keeping viewing simple.
for-each cannot modify the original array/collection's structure (like removing elements) safely during iteration — doing so throws a ConcurrentModificationException for most collections.
Exam trap: reassigning the for-each loop variable inside the body does not change the element in the underlying array or collection; it only changes the local copy for that iteration.
4. Example
public class ForLoopDemo {
public static void main(String[] args) {
// Classic for loop: print squares of 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i + " squared = " + (i * i));
}
// Enhanced for-each loop over an array
int[] numbers = {10, 20, 30};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum = " + sum);
}
}5. Output
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
Sum = 606. Key Takeaways
- Classic for loop: initialization runs once, condition checked before each iteration, update runs after each iteration.
- All three parts of a classic for loop are optional;
for (;;)creates an infinite loop. - for-each simplifies iteration over arrays and Iterable collections but hides index access.
- for-each cannot be used to reassign elements back into the original array via the loop variable.
- Modifying a collection's structure during for-each iteration risks ConcurrentModificationException.
- Use classic for loop when index-based logic (like reverse order or step size) is required.
Practice what you learned
1. What does `for (;;) { }` represent in Java?
2. Which interface must a collection implement to be used in a for-each loop?
3. In a classic for loop `for (int i = 0; i < 5; i++)`, when is the condition checked?
4. What happens if you reassign the loop variable inside a for-each loop over an int array?
5. Which loop type is Iterable-based and does not expose an index variable directly?
Was this page helpful?
You May Also Like
while and do-while Loops in Java
Learn the difference between Java's entry-controlled while loop and exit-controlled do-while loop, including syntax, semantics, and common pitfalls.
break and continue in Java
Understand how break and continue alter loop execution in Java, including labeled break/continue for controlling nested loops directly.
Arrays in Java
Learn how Java arrays store fixed-size, homogeneous collections of elements on the heap, including declaration, default values, and common runtime errors.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics