Syntax
The syntax of the enhanced for loop is straightforward & easy to remember. Here's the general syntax:
for (dataType element : arrayOrCollection) {
// Code to be executed for each element
}
Let's look at the components of the enhanced for-loop syntax:
- `dataType`: It specifies the data type of the elements in the array or collection. It should match the type of elements being iterated over.
- `element`: It is a variable that represents the current element being processed in each iteration. You can choose any valid variable name.
- `arrayOrCollection`: It is the array or collection that you want to iterate over. It can be an array of primitives, an array of objects, or any collection that implements the Iterable interface.
The enhanced for loop automatically iterates over each element in the array or collection, assigning the current element to the `element` variable in each iteration. The loop continues until all elements have been processed.
How it works
Under the hood, the enhanced for loop is a simplified version of the traditional for loop. When you use the enhanced for loop, the Java compiler transforms it into an equivalent traditional for loop behind the scenes.
Let’s look at the step-by-step that how the enhanced for loop works:
1. The compiler retrieves the iterator for the array or collection being iterated over.
2. The loop starts & the iterator's `hasNext()` method is called to check if there are more elements to process.
3. If `hasNext()` returns `true`, the iterator's `next()` method is called to retrieve the next element.
4. The retrieved element is assigned to the `element` variable declared in the loop.
5. The body of the loop is executed, allowing you to perform operations on the current element.
6. Steps 2-5 are repeated until `hasNext()` returns `false`, indicating that all elements have been processed.
7. The loop ends, & program execution continues with the next statement after the loop.
By using the enhanced for loop, you don't need to worry about the internal mechanics of iterators or index management. The Java compiler takes care of those details for you, providing a more convenient & straightforward way to iterate over elements.
For-each loop Example: Traversing the array elements
Let's take a look at an example of using the enhanced for loop to traverse elements in an array:
Java
public class ArrayTraversal {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Array elements:");
for (int num : numbers) {
System.out.println(num);
}
}
}

You can also try this code with Online Java Compiler
Run Code
In this example, we have an integer array called `numbers` that contains five elements. We use the enhanced for loop to iterate over each element in the array.
The loop starts with the keyword `for`, followed by a pair of parentheses. Inside the parentheses, we declare a variable `num` of type `int`, which represents the current element being processed in each iteration. The colon (`:`) separates the variable declaration from the array `numbers` that we want to iterate over.
In each iteration, the current element is assigned to the `num` variable. The body of the loop is executed, which in this case, simply prints the value of `num` to the console.
The output of this program will be:
Array elements:
1
2
3
4
5
As you can see, the enhanced for loop automatically iterates over each element in the `numbers` array, allowing us to perform operations on each element without the need for explicit index management.
For-each loop Example: Traversing the collection elements
In addition to arrays, the enhanced for loop can also be used to traverse elements in collections that implement the Iterable interface.
Let's take a look at an example:
Java
import java.util.ArrayList;
import java.util.List;
public class CollectionTraversal {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
System.out.println("Fruits in the list:");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

You can also try this code with Online Java Compiler
Run Code
In this example, we have an ArrayList called `fruits` that contains four elements of type String. We use the enhanced for loop to iterate over each element in the `fruits` collection.
The syntax of the enhanced for loop remains the same as in the previous example. We declare a variable `fruit` of type `String` to represent the current element being processed in each iteration. The colon (`:`) separates the variable declaration from the `fruits` collection that we want to iterate over.
In each iteration, the current element is assigned to the `fruit` variable. The body of the loop is executed, which prints the value of `fruit` to the console.
The output of this program will be:
Fruits in the list:
Apple
Banana
Orange
Mango
The enhanced for loop seamlessly works with collections, allowing us to iterate over elements without the need for explicit iterator management.
It's important to note that the enhanced for loop can be used with any collection that implements the Iterable interface, such as ArrayList, LinkedList, HashSet, TreeSet, etc.
Frequently Asked Questions
Can the enhanced for loop be used with primitive data types?
Yes, the enhanced for loop can be used with arrays of primitive data types, such as int, double, char, etc.
Is it possible to modify elements using the enhanced for loop?
No, the enhanced for loop provides read-only access to elements. To modify elements, you need to use the traditional for loop or an iterator.
Can the enhanced for loop be used with nested loops?
Yes, you can use the enhanced for loop in nested loops to iterate over elements of nested arrays or collections.
Conclusion
In this article, we have learned about the enhanced for loop in Java, which provides a concise & convenient way to iterate over elements in arrays & collections. We understood the advantages of using the enhanced for loop, its syntax, & how it works behind the scenes. We also looked at examples of traversing array elements & collection elements using the enhanced for loop. The enhanced for loop improves code readability, reduces the chances of errors, & simplifies the iteration process, making it a valuable tool in Java programming.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.