Nearby lessons
23 of 125Java - for-each (Enhanced for) Loop
📌 What You Will Learn
- The small building blocks of Java: tokens
- All 8 primitive data types with their ranges
- Type casting — implicit and explicit
- Control statements: if, switch, loops
- Arrays — single, double and jagged
- Variable length arguments (var-args)
for-each (Enhanced for) Loop is a core concept of the Java language. This lesson explains Enhanced for-loop (for-each) and Index Loop vs for-each Loop with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Enhanced for-loop (for-each)
Java 5 gave us a simpler loop to read every element of an array or collection — no index needed:
Example01
Enhanced for-loop (for-each)
Example02
Index Loop vs for-each Loop
The classic material explains why the for-each (enhanced for) loop is better for reading arrays and collections:
| Point | Index loop (for i=0...) | for-each loop |
|---|---|---|
| Loop variable | You manage it yourself | None needed |
| Condition check | Every iteration (uses resources) | Automatic |
| Increment/decrement | You write it | Automatic |
| Risk of index errors | Possible (ArrayIndexOutOfBoundsException) | None |
| Readability | Lower | Higher |
Trainer's Note: Use the index loop when you need the position (like a[i] in a pattern). Use for-each when you only need the values — it is simpler and safer. For-each also works on all Collections, as we see in Chapter 15.
Example03
📝 Key Takeaways
- Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
- Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
- Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
- if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
- Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
- Var-args (int... x) lets a method take any number of arguments.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1