Enhanced loop in java is also known as the "for-each" loop and it provides a simpler and more readable way to iterate over arrays, collections, and other objects that implement the Iterable interface. In this short article, we will discuss what an enhanced loop is in java and how we can create one. Moreover, we will go through various examples of enhanced loop java.
What is Enhanced for loop in Java?
The enhanced for loop, also known as the "for-each" loop, is a feature introduced in Java 5 that provides a simpler and more concise way to iterate over arrays, collections, and other objects that implement the Iterable interface. This feature was introduced to reduce the amount of code required to iterate over collections and to make the code more readable.
The syntax of the enhanced for loop is as follows:
for (element_type element : collection) {
// loop body
}
In this syntax, element_type
is the data type of the elements in the collection, element is the name of the variable that will hold each element as it is iterated over, and collection is the collection that will be iterated over.
Examples of the Enhanced for Loop in java
Now we will go through various examples of the enhanced loop in java to understand how and where we can use it.
Example-1: Iterating Over an Array
We can use the enhanced loop to iterate over an array as shown below:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
}
}
Output:
1
2
3
4
5
This code creates an array of integers named numbers and initializes it with five values. It then uses the enhanced for loop to iterate over the array, assigning each element to the variable number and printing it to the console.
Example 2: Iterating Over a List
We can also use the enhanced loop to iterate over a list as shown below:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name);
}
}
}
Output:
Alice
Bob
Charlie
This code creates a list of strings named names and adds three strings to it. It then uses the enhanced for loop to iterate over the list, assigning each element to the variable name and printing it to the console.
Example 3: Iterating Over a Map
Now let us take an example and see how we can iterate over a map using the enhanced loop in Java.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 100);
scores.put("Bob", 75);
scores.put("Charlie", 90);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + " scored " + score);
}
}
}
Output:
Alice scored 100
Bob scored 75
Charlie scored 90
This code creates a map of string keys and integer values named scores and adds three key-value pairs to it. It then uses the enhanced for loop to iterate over the map, assigning each key-value pair to the variable entry. The loop body extracts the key and value from the entry and assigns them to the variables' names and scores, respectively. It then prints a message to the console indicating the name and score for each key-value pair in the map.
Example 4: Perform sum of Array
Suppose you have an array of integers and you want to calculate the sum of all the elements in the array. Here is an example of using an enhanced for loop to do this:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("The sum of the numbers is: " + sum);
In this example, the enhanced for loop iterates over each element of the numbers
array and adds it to the sum
variable. After the loop has finished executing, the total sum of the array is printed to the console.
Example 5: Filtering a List
Suppose you have a list of strings and you want to filter out all the strings that start with a certain prefix. Here is an example of using an enhanced for loop to do this:
List<String> words = Arrays.asList("apple", "banana", "orange", "pear", "peach");
List<String> filteredWords = new ArrayList<>();
String prefix = "p";
for (String word : words) {
if (word.startsWith(prefix)) {
filteredWords.add(word);
}
}
System.out.println("Words that start with \"" + prefix + "\": " + filteredWords);
In this example, the enhanced for loop iterates over each element of the words
list and checks if it starts with the specified prefix. If it does, the word is added to a new list called filteredWords
. After the loop has finished executing, the filtered list is printed to the console.
Limitations of the Enhanced For Loop in Java
One of the main limitations of the enhanced for loop is that it cannot be used to modify the collection being iterated over. This is because the enhanced for loop is designed to provide a simple and concise way to iterate over a collection without having to worry about index variables and other implementation details. When you use an enhanced for loop, you're essentially asking the Java runtime to handle the iteration for you, and you don't have direct access to the underlying data structure.
Here's an example that demonstrates this limitation:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (int number : numbers) {
if (number == 2) {
numbers.remove(number);
}
}
}
}
In this code, we create a list of integers named numbers and add three values to it. We then use an enhanced for loop to iterate over the list, checking each element to see if it's equal to 2. If it is, we try to remove it from the list using the remove() method. However, when we run this code, we get a ConcurrentModificationException at runtime. This exception occurs because we're trying to modify the list while we're still iterating over it with the enhanced for loop. The enhanced for loop is not designed to handle this kind of modification, so it throws an exception to alert us to the problem.
To avoid this problem, you should use a standard for loop with an index variable when you need to modify a collection while iterating over it. This allows you to keep track of the current index and modify the collection safely:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (int i = 0; i < numbers.size(); i++) {
int number = numbers.get(i);
if (number == 2) {
numbers.remove(i);
i--;
}
}
}
}
In this code, we use a standard for loop with an index variable i to iterate over the list. We then use the get()
method to retrieve each element at the current index, and we modify the list safely by using the remove()
method with the current index. We also decrement the index variable if we remove an element to avoid skipping over any elements.
Frequently Asked Questions about Enhanced for loop in Java
What is the difference between a traditional for loop and an enhanced for loop?
The traditional for loop is used to iterate over a range of values, while the enhanced for loop is used to iterate over elements in an array or collection. The enhanced for loop is more concise and easier to read than the traditional for loop.
What data types can be used in an enhanced for loop?
The enhanced for loop can be used with arrays of any data type and with any collection that implements the Iterable
interface.
Can I modify the elements of an array or collection while using an enhanced for loop?
Technically, yes, but it is not recommended. If you modify the elements of an array or collection while iterating over it with an enhanced for loop, it can cause unpredictable behavior. It is recommended to use a traditional for loop if you need to modify elements of the array or collection.
Can I use an enhanced for loop to iterate over a Map?
No, you cannot use an enhanced for loop to iterate over a Map. Maps are not iterable, but you can iterate over their keys, values, or entries using the keySet()
, values()
, or entrySet()
methods, respectively.
Can I use multiple variables in an enhanced for loop?
No, an enhanced for loop only allows one variable to represent each element in the array or collection. If you need to access multiple values or properties of each element, you can use a traditional for loop instead.
Summary
In Java, an enhanced for loop (also known as a "for-each" loop) is a language feature that provides a simpler and more concise way to iterate over arrays, collections, and other data structures. In this short article, we discussed what is enhanced loop is and how we can use it in the java programming language.
Further Reading