Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
Now Reading
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
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.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...