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
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
For each loop in Java is a technique to traverse multiple arrays and collections. For each loop in Java is mainly used to iterate through array and collection elements and provides the advantages of eliminating bugs and errors in codes to present it in a more convenient form. It is also known as the enhanced for loop Java ArrayList because it functions with array and collection elements.
Java for each loop traverses all elements one by one, and as it does not function on an index basis, you cannot skip any element. Java for each loop is increasingly used because it helps to draft the codes in a way that is user readable.
This is a detailed tutorial that will walk you through the concept of for each loop in Java. It will also dicuss the differences between “for each” loop and “for” loop.
For each or “for-each” loop is used in Java, PHP, Python, etc, to traverse arrays and collections. It is a traversing technique program that is used in decision-making. The program starts with the keyword 'for.’ After that, you declare a variable of the same data type and specify the array name at the end. It is mainly used for iteration and traversing purposes and works well with ArrayList and collections.
Java for each loop syntax is:
for (type var : array)
{
statements using var;
}
Here's a breakdown of the different components:
public class main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Using for each loop to traverse the array elements
for (int number : numbers) {
System.out.println(number);
}
}
}
In this example, we have an array called numbers containing five elements. We use the "for each" loop to iterate over each array element. The loop variable number takes the value of each element in the array, and we print it using System.out.println().
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");
// Using for each loop to traverse the collection elements
for (String name : names) {
System.out.println(name);
}
}
}
In this example, we have a List collection called names that stores strings. We use the "for each" loop to iterate over each element in the collection. The loop variable name takes the value of each element in the collection, and we print it using System.out.println().
You should use for each loop when you want to run a successful loop through all the values in a list or array. When you do not wish to change any values in the loop or remove anything, then using for each loop is the best way.
You should not use for each loop in Java when you want to perform the function of filtering. To filter, the program should have access to the iterator, but in the case of Java for each loop, the iterator is hidden. Hence, you should avoid using this program while trying to filter. Also, you cannot call remove because the iterator is hidden, so you should not use it for loops where you want to remove or replace elements in an ArrayList.
Let's look at some real-world applications of the concept with Java for each loop example:
public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};
// Using for each loop to iterate over the array elements
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
In this example, we have an array called fruits containing three elements. We use the "for each" loop to iterate over each element in the array. The loop variable fruit takes the value of each element in the array, and we print it using System.out.println().
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> hashMap = new HashMap<>();
// Add some key-value pairs
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Orange");
hashMap.put(4, "Mango");
// Iterate over the HashMap using for each loop
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In this example, we create a HashMap called hashMap and add some key-value pairs to it. Then, we use a for each loop to iterate over the entrySet() of the HashMap. Each entry in the entrySet() represents a key-value pair in the HashMap. Inside the loop, we retrieve the key and value of each entry using the getKey() and getValue() methods, respectively.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of custom objects
List<Person> people = new ArrayList<>();
// Add some people to the list
people.add(new Person("John", 25));
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 28));
people.add(new Person("Emily", 22));
// Traverse the list using for each loop
for (Person person : people) {
// Perform operations on each person
String name = person.getName();
int age = person.getAge();
// Print the person's information
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Adult: " + (age >= 18));
System.out.println("------------------------");
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
In this example, we have a custom class called Person that represents a person with a name and age. We create a List called people and add some Person objects to it.
Using a for each loop, we iterate over each Person object in the people list. Inside the loop, we retrieve the person's name and age using the getName() and getAge() methods. Then, we perform some operations on the person, such as determining if they are an adult based on their age.
Finally, we print the person's information, including their name, age, and whether they are adults. A line separates each person's information.
Java for each loop is a convenient traversing and iteration technique for users. It has the following advantages to offer:
Some of the limitations that are there when using for each loop in Java are stated as follows:
For loop | For each loop |
For loops runs and executes a set of code until the result is returned as false. | For each loop executes a set of code through each element in an ArrayList or collection. |
For loops are independent of any object or object collection and can run code with or without it. | The for each loop can execute codes only with object collection and not without it. |
For loop is a general loop and can be used for various purposes. | for each loop is exclusively intended to operate with Collections or IEnumerables objects. |
For each loop in Java is a valuable control flow statement that is used in traversing items or objects in a collection. It helps reduce errors and bugs in a program and creates an iterative system in programming. By learning the functionality and importance of Java for each loop, developers can use it efficiently to run programming codes while minimizing the possibility of errors. You can learn more about Java loops and other concepts from curated courses offered by online learning platforms like upGrad.
1. Does Python have a for each loop?
There is no exclusive for each loop in Python. However, Python consists of two main loops: for loop and while loop.
2. What is the for each loop in PHP?
For each loop in PHP is the same as that in Java and performs the same functions. It allows users to iterate objects in an array list or collection.
3. What is the importance of for each loop in Java?
For each loop is a decision-making statement that allows users to do away with the possibility of errors and bugs in a program and also performs traversing action.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.