For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
In Java, looping through elements is a task you often perform while building applications. Whether you are processing an array of numbers or displaying items from a list, loops help repeat actions efficiently. The for-each loop makes this process simpler and easier to read.
Instead of worrying about index values or running into errors like ArrayIndexOutOfBoundsException, you can directly access each element. It is like scrolling through photos in your gallery without counting how many you have seen.
This blog will explain what the For-Each Loop in Java is, how it works, its syntax, when to use it, when to avoid it, and common use cases.
Software engineering courses can help you understand these concepts through structured learning and hands-on practice.
The for-each loop (also called an enhanced for loop) was introduced in Java 5. It allows you to iterate through arrays and collections without using an index. Think of it like scanning every item in a list, one by one, without checking its position.
Syntax:
for (dataType variable : arrayOrCollection) {
// loop body
}
Example:
int[] numbers = {1, 2, 3};
for (int num : numbers) {
System.out.println(num);
}
Output:
1
2
3
Explanation: Each element from the array is printed. No index is needed.
Unlock a high-paying career with the following full-stack development courses:
Use a for-each loop when you want to access every element one by one without modifying the structure or needing an index.
Example:
List<String> cities = List.of("Delhi", "Mumbai", "Bangalore");
for (String city : cities) {
System.out.println(city);
}
Output:
Delhi
Mumbai
Bangalore
Explanation: Ideal for read-only iteration of all elements.
Must read: Java ArrayList forEach
The for-each loop is not suitable in certain situations. Avoid using it if you need to:
Example:
int[] nums = {10, 20, 30};
for (int num : nums) {
num = num + 5;
}
System.out.println(nums[0]);
Output:
10
Explanation: Modifying the loop variable doesn't affect the original array.
Must explore: Control Statements in Java: What Do You Need to Know in 2025
Arrays are one of the most common structures used with for-each loops in Java.
Example – Finding Maximum:
int[] numbers = {5, 3, 9, 1, 7};
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum: " + max);
Output:
Maximum: 9
Explanation: The loop checks each value to find the maximum.
Must explore: Comprehensive Guide to Exception Handling in Java
Java collections like List and Set are compatible with for-each loops.
Example:
List<String> animals = List.of("Cat", "Dog", "Elephant");
for (String animal : animals) {
System.out.println(animal);
}
Output:
Cat
Dog
Elephant
Explanation: Each item in the list is printed without needing an index.
Also read: How to Iterate Any Map in Java?
Maps can’t be used directly with for-each. But you can loop through their entrySet().
Example:
Map<String, Integer> scores = Map.of("Alisha", 90, "Bhanu", 85);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output:
Alisha: 90
Bhanu: 85
Explanation: We iterate through key-value pairs using entrySet().
Also explore: Factorial Using Recursion in Java
Use traditional for loop when:
int[] data = {10, 20, 30};
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
for (int value : data) {
System.out.println(value);
}
Both have their place in Java programming.
Java 8 introduced the .forEach() method with Streams for functional-style coding.
Example:
List<String> names = List.of("Jhanvi", "Jiya", "Alisha");
names.forEach(name -> System.out.println(name));
Output:
Jhanvi
Jiya
Alisha
Explanation: A lambda expression prints each name from the Java stream.
Also read: Do While Loop in Java: Syntax, Examples, and Practical Applications
The for-each loop is widely used in Java applications where simple, readable iteration is required without modifying the collection. Below are some common use cases and real-world applications. Let’s understand how For-each Loop in Java is used in real-world.
When fetching data from a database, results are often stored in a list or array. A for-each loop helps in displaying these records easily.
List<String> employees = Arrays.asList("Jiya", "Meera", "Amit");
for (String employee : employees) {
System.out.println("Employee Name: " + employee);
}
Output:
Employee Name: Jiya
Employee Name: Meera
Employee Name: Amit
Explanation: Each record is accessed one by one without the need for indexes.
For-each loops are useful when checking a list of user inputs for empty or invalid values.
String[] inputs = {"email", "password", ""};
for (String input : inputs) {
if (input.isEmpty()) {
System.out.println("One of the input fields is empty");
}
}
Output:
One of the input fields is empty
Explanation: You can quickly validate all entries without managing index positions.
When you have a list of options for dropdowns, for-each can render them in user interfaces.
String[] countries = {"India", "USA", "Germany"};
for (String country : countries) {
System.out.println("Dropdown Option: " + country);
}
Output:
Dropdown Option: India
Dropdown Option: USA
Dropdown Option: Germany
Explanation: Common in web and GUI applications to list available options.
For-each is ideal for processing large arrays of sensor data, like temperature or pressure readings.
double[] temperatures = {98.6, 101.2, 97.5};
for (double temp : temperatures) {
if (temp > 100.0) {
System.out.println("High temperature alert: " + temp);
}
}
Output:
High temperature alert: 101.2
Explanation: Efficiently scans through each value to find outliers.
For-each loops help in printing log entries or audit records for system monitoring or debugging.
List<String> logs = Arrays.asList("Login success", "Password changed", "Logged out");
for (String log : logs) {
System.out.println("Audit Log: " + log);
}
Output:
Audit Log: Login success
Audit Log: Password changed
Audit Log: Logged out
Explanation: You can loop through logs without needing to track log entry numbers.
The for-each loop in Java simplifies the process of iterating over arrays and collections by eliminating the need to manage indexes manually. It enhances code readability and reduces common errors like ArrayIndexOutOfBoundsException. While it is perfect for reading or processing elements, it has limitations such as not supporting element modification or index access. Knowing when to use or avoid it helps you write cleaner, safer, and more efficient Java programs that are easier to maintain and understand.
No, you cannot modify original elements directly inside a for-each loop, especially for arrays or primitive types. The loop variable is a copy of the element, not a reference. To modify elements, use a traditional for loop with an index.
Yes, you can use a for-each loop with arrays or collections of custom objects. As long as the object is stored in an array or a class implementing the Iterable interface, the for-each loop works without any additional setup.
No, the for-each loop does not expose the index of the current element. If you need index-based operations, use a traditional for loop. Alternatively, maintain a separate counter variable inside the for-each loop, but it requires manual incrementing.
Yes, for-each loops can iterate over a Set because Set implements the Iterable interface. However, keep in mind that sets do not maintain any specific order, so the iteration order may not match the insertion or sorting sequence.
Removing elements during a for-each loop using remove() causes a ConcurrentModificationException. The collection structure changes while iterating. To avoid this, use an Iterator with its remove() method, or collect elements separately and remove them after iteration.
For-each loops offer better readability but are not always faster. Traditional for loops may be more efficient for arrays, especially when index reuse or partial iteration is needed. The performance difference is minor and often not noticeable in real scenarios.
No, a single for-each loop can iterate over only one array or collection at a time. To iterate over multiple collections, you’ll need separate loops or merge them into one structure before iteration. Java doesn’t support multi-source for-each iteration.
Yes, for-each loops support multidimensional arrays using nested loops. The outer loop accesses each sub-array, and the inner loop accesses elements of those sub-arrays. However, this approach assumes rectangular arrays where inner dimensions are consistent.
For-each loops are not inherently thread-safe. If another thread modifies the collection during iteration, it may cause a ConcurrentModificationException. To avoid this, use concurrent collections or proper synchronization when accessing shared data in a multithreaded environment.
Yes, Java allows the use of break and continue statements in a for-each loop. These help control the flow—break exits the loop, while continue skips the current iteration and moves to the next element in the collection.
Any class that implements the Iterable interface can be used in a for-each loop. This includes core collection classes like ArrayList, HashSet, and LinkedList, making for-each a convenient way to traverse these data structures.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.