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
JCode Cell
1for (type variableName : collectionOrArray) {
2 // variableName holds each element one by one
3}

Enhanced for-loop (for-each)

Example02
JCode Cell
1class ArrayDemo {
2 public static void main(String[] args) {
3 int[] numbers = {10, 20, 30, 40, 50};
4 int sum = 0;
5 for (int n : numbers) { // for-each
6 sum = sum + n;
7 }
8 System.out.println("Sum = " + sum);
9 }
10}
Output
Sum = 150

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
JCode Cell
1int[] a = {1, 2, 3, 4, 5};
2 
3// index loop
4for (int i = 0; i < a.length; i++) {
5 System.out.println(a[i]);
6}
7 
8// for-each (Java 5+)
9for (int x : a) {
10 System.out.println(x);
11}
📝 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