For Each Loop in Java: Enhanced For Loop
The for each loop in Java (also referred to as enhanced for loop) is an extended feature of Java language that was introduced with the J2SE 5.0 release. This feature is specially designed to retrieve elements of the array efficiently rather than using array indexes.
Java for-each loop can also be used to retrieve elements of a collection. A collection represents a group of elements as integer values, strings, or objects.
Enhanced for loop repeatedly executes a group of statements for each element of the collection. It can execute as many times as a number of elements in the collection.
Syntax of For Each Loop in Java
The general syntax for using for each loop in Java programming is as follows:
for(data_type identifier : expression)
{
// Code block to be executed for each element.
}
In the above syntax,
- data_type represents the data type of elements in the collection or object used;
- Identifier specifies the name of an iteration variable that receives elements from a collection, one at a time, from beginning to end;
- expression is an object of java.lang.Iterable interface or an array.
Note: Unlike some other programming languages, such as C#, that implement a for-each loop by using foreach keyword. But, Java language added the for each capability by enhancing the for statement. The advantage of enhancing is that no new keyword is needed, and no preexisting code is broken.
Therefore, the for each loop is also known as enhanced for loop in Java. Professional programmers generally use enhanced for loop in the industry.
For Each Loop Examples
Let’s understand the above syntax with the help of an example program. Consider the following examples below:
Example 1:
// Create an array of three elements.
int numarr[] = {10, 20, 30};
// Applying for loop to iterate over elements.
for(int i = 0; i <= 3; i++)
{
if(numarr[i] > 5 && numarr[i] < 40)
System.out.println("Selected value: " +numarr[i]);
}
// This code is equivalent to the following code:
int numarr[] = {10, 20, 30};
// Applying for each loop to iterate over elements.
for(int i : numarr)
{
if(i > 5 && i < 40)
System.out.println("Selected value: " +i);
}
In this example, we have created an array of three elements and store in a variable named numarr. Then, we have used for each loop to iterate over each element in the “numarr” array.
According to the syntax of for each loop, int represents the data type, i represents the name of temporary variable used for storing each element during iteration, and numarr is an iterable object being traversed.
The enhanced for loop iterates over each element in the array and prints the result. Thus, we can use Java for each loop to track elements of an array efficiently.
In the same style, we can also use for each loop to track elements of the collection, as follows:
Example 2:
// Creating an object of ArrayList of type String.
ArrayList<String> cities = new ArrayList<String>();
// Adding elements in the array list.
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Dhanbad");
cities.add("Kolkata");
// Iterating array list using enhanced for loop.
for(String city : cities)
{
System.out.println(city);
}
In this example, we have created an ArrayList named “cities” of type string. We have added four string elements to the list. Then, we have used the for-each loop to iterate through each element in the “cities” list. If we compare the syntax of for each loop with the above code, we will get the following information:
- string represents the data type of elements,
- city represents the name of iteration variable used to store each element during the iteration,
- cities represents an iterable object (ArrayList) being traversed.
The enhanced for loop iterates through each element in the array list and prints its value using System.out.println(city). The output will display the name of cities Delhi, Mumbai, Dhanbad, and Kolkata on separate lines.
Java For Each Loop Example Programs
Let’s take an example program where we retrieve elements of an array one by one using for-each loop and display it on the console.
Example 1:
package javaProgram;
public class Test {
public static void main(String[] args)
{
// Create an array of 5 elements.
String cities[] = {"Dhanbad", "Mumbai", "Delhi", "New York", "Godda" };
// Using for each loop to retrieve elements (i.e. cities) from an array.
System.out.println("Name of cities:");
for(String city : cities)
{
System.out.println(city); // city represents each element of an array.
}
}
}
Output: Name of cities: Dhanbad Mumbai Delhi New York Godda
Let’s consider another example program where we will calculate the sum of the first 10 numbers in Java using each for loop and display it on the console.
Example 2:
package javaProgram;
public class Test {
public static void main(String[] args)
{
// Declare an array of 10 elements.
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// Iterating elements using for each loop to display and sum the values.
for(int x : nums) {
sum += x;
}
System.out.println("Sum: " + sum);
}
}
Output: Sum: 55
Suppose in the above program, we want to calculate only the sum of five numbers out of 10 numbers. Here, we will use break statement. Let’s write the code for it.
Example 3:
package javaProgram;
public class Test {
public static void main(String[] args)
{
// Declare an array of 10 elements.
int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// Iterating elements using for-each loop to display and sum the values.
for(int x : nums) {
sum += x;
if(x == 5) break; // stop the loop when x is equal to 5.
}
System.out.println("Sum of first 5 elements: " + sum);
}
}
Output: Sum of first 5 elements: 15
As you can observe in the example program, the for-each loop stops after the fifth element has been obtained.
Iterating Elements of Multidimensional Array
We can also use the Java enhanced for loop on multidimensional arrays. In Java, multidimensional arrays consist of arrays of arrays. Let’s understand the example code below.
Example 4:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int sum = 1;
// Create an object of 2D array.
int nums[ ][ ] = new int[3][5];
for(int i = 1; i < 3; i++)
{
for(int j = 1; j < 5; j++)
{
nums[i][j] = i * j;
// Using for each loop to display and sum the values.
for(int x[ ] : nums)
{
for(int y : x)
{
sum += y;
}
}
}
}
System.out.println("Sum: " + sum);
}
}
Output: Sum: 101
Let’s take an example in which we will search for an element from an array. If the element is found, it will stop. Look at the example code to understand better.
Example 5:
package javaProgram;
public class SearchTest {
public static void main(String[] args)
{
// Creating an array object of 8 elements.
int nums[] = { 1, 8, 3, 7, 5, 6, 10, 4 };
int val = 10;
boolean found = false;
// Searching for an element value 10 from an array using Java for each loop.
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
Output: Value found!
Advantages of For-Each Loop Over Traditional For Loop
The for-each loop provides several advantages over the traditional for loop in Java:
- The syntax of the for-each loop is very simple and concise, resulting in more concise code compared to traditional loops.
- The for-each loop enhances code readability as compared to the traditional for loop in Java.
- As there is no explicit use of indices, the for-each loop helps avoid common errors, such as “IndexOutOfBoundException”.
- With the for each loop, we can easily iterate over elements in arrays and collections without the need to manage indices explicitly.
- The enhanced for loop makes the code more concise and easier to understand.
Limitations of For Each Loop (or Enhanced For Loop)
Although the for-each loop provides several significant advantages, but it does have some limitations and potential pitfalls:
- In Java, the for each loop is designed for read-only access to elements. If we try to modify it during the iteration, we may get to runtime exceptions.
- The for each loop is not suitable when we need to access elements by index.
- It may not be suitable in certain situations, such as looping backward or skipping certain elements.
When to Use For Each Loop in Java Programming?
For each loop finds extensive use in scenarios where we need to iterate over all elements of an array or collection sequentially. Some common use cases include:
- Calculating the sum, average, or other aggregate values of an array of numbers.
- Searching for specific elements in a collection.
- Printing or displaying elements to the user.
- Copying elements from one collection to another.
- Filtering elements based on certain criteria.
- Use for each loop with custom objects if the collection contains instances of the custom class.
- Use the enhanced for loop if you need the guarantee order of elements in the collection, like list.