For-Each Loop in Java (Simplest Way to Loop Through Arrays)

βœ… What is a For-Each Loop?

The for-each loop (also called the enhanced for loop) in Java is a special type of loop used to iterate over arrays and collections. It is simpler and more readable than the traditional for loop when you only need to access each element and do not need the index.

This loop is ideal when you’re working with arrays, ArrayList, or other collections, and you just want to perform an action on each item.


🧠 Syntax of the For-Each Loop

for (dataType variable : arrayOrCollection) {
// Code to be executed
}
  • dataType: The type of elements in the array or collection.

  • variable: A temporary variable that holds each element.

  • arrayOrCollection: The array or collection you’re looping through.


🎯 Example 1: For-Each Loop with an Integer Array

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

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

Output:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

🎯 Example 2: For-Each Loop with a String Array

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

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

Output:

Fruit: Apple
Fruit: Banana
Fruit: Mango
Fruit: Orange

🚫 Limitations of For-Each Loop

  • You cannot modify elements directly using the for-each loop (you don’t have access to the index).

  • Not suitable when you need to skip, reverse, or partially loop through data.

  • Not ideal when working with multi-dimensional arrays if you need precise control.


βœ… When to Use For-Each Loop

  • You just want to read or print all items in an array or collection.

  • You don’t care about the index position of each element.

  • You want cleaner and more readable code.


πŸ†š For vs For-Each: Quick Comparison

Feature For Loop For-Each Loop
Access by index βœ… Yes ❌ No
Suitable for updates βœ… Yes ❌ No (read-only)
Readability ❌ Less readable βœ… More readable
Use case General looping Reading items only

The for-each loop is one of the most elegant ways to read elements in Java. Use it when you need simplicity and readability, especially for tasks like printing arrays or looping through lists.

Related Posts