Nearby lessons

23 of 125

Java - 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
Loading editor…

Enhanced for-loop (for-each)

Example02
Loading editor…

Index Loop vs for-each Loop

The classic material explains why the for-each (enhanced for) loop is better for reading arrays and collections:

PointIndex loop (for i=0...)for-each loop
Loop variableYou manage it yourselfNone needed
Condition checkEvery iteration (uses resources)Automatic
Increment/decrementYou write itAutomatic
Risk of index errorsPossible (ArrayIndexOutOfBoundsException)None
ReadabilityLowerHigher
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
Loading editor…
📝 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 Questions
Progress: 0 / 1

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.