Java For-Each Loop

🔁 Java For-Each Loop (Enhanced for Loop)

The for-each loop is used to iterate over arrays or collections in a simpler and more readable way than a traditional for loop.
It eliminates the need for an index variable.


Syntax

for (dataType item : arrayOrCollection) {
// code using item
}
  • item → current element of the array/collection

  • arrayOrCollection → the array or collection being iterated


📘 Example 1: Iterating Over an Array

public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};

for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

📌 Output:

Apple
Banana
Orange

📘 Example 2: Iterating Over Numbers

public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

for (int num : numbers) {
System.out.println(num);
}
}
}


📘 Example 3: Sum of Array Elements

public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;

for (int num : numbers) {
sum += num;
}

System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 15

📘 Example 4: Iterating Over a Collection (ArrayList)

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("BMW");
cars.add("Audi");
cars.add("Tesla");

for (String car : cars) {
System.out.println(car);
}
}
}

📌 Output:

BMW
Audi
Tesla

🔹 Advantages of For-Each Loop

  1. Readable – no need to manage index variables

  2. Safe – avoids out-of-bounds errors

  3. Quick – easier to iterate over arrays and collections


🔹 Limitations

  • Cannot modify the elements of the array/collection directly

  • Cannot get the index of the element (use traditional for loop if needed)

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *