For each loop in Java
This blog will help you learn the concepts of for each loop in Java. You can use it to iterate through the elements of an array or collection without using an index variable.
For-each loop in Java helps you go through a group of items one by one, just like checking off items on a shopping list. It makes the code easier to read and understand. It is super useful while working with large data sets, like an array. It’s like a helper who goes through the list for you.
- for-each loop uses “for” keyword.
- Declare a variable same type as the array, followed by a colon, and array name.
- Use the declared variable in the loop body, not indexed array element.
- Commonly used to iterate arrays or Collections.
A “for each” loop in Java is a type of loop that added in Java version 5.0. It allows you to iterate through the elements of an array or collection without using an index variable.
Read More: For Loop in Java
The basic syntax for a for each loop is:
for (Type variable : collection) { // code to be executed for each element }
For example:
//using a for each loop to print out the elements of an array of integersint[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println(num);}
This will output the numbers 1 through 5, one per line.
It’s important to note that the for-each loop operates on the elements, not on the indexes, so you cannot use the for-each loop for modify elements of array, if you wish to modify element in array you should use normal for-loop.
Here’s another example,
//for-each loop that iterates through a List of StringsList<String> list = Arrays.asList("A","B","C","D");for(String str : list) { System.out.println(str);}
Scenario Based Example: For each Loop in Java
Let’s say you’re building a shopping cart application for an online store. You have a Cart class that contains a list of Item objects, and each Item has a name, price, and quantity. You want to write a method that calculates the total cost of all items in the cart. Here’s how you might use a for each loop to accomplish this:
class Item { String name; double price; int quantity;
// constructor to initialize the properties public Item(String name, double price, int quantity) { this.name = name; this.price = price; this.quantity = quantity; } //other methods like getters for properties go here}
class Cart { List<Item> items = new ArrayList<>();
// other methods that perform other operations on cart items go here
public double getTotalCost() { double total = 0.0; for (Item item : items) { //iterating through each item in items list and adding their total cost to the variable total += item.getPrice() * item.getQuantity(); } //returning total cost return total; }}
- In the given example, the getTotalCost() method uses a for each loop to iterate through the items list and add up the total cost of all the items.
- The for (Item item : items) loop goes through all items in the items list.
- During each iteration, the item variable will be set with the current item in the list, allowing you to access the item’s properties.
- The calculation item.getPrice() * item.getQuantity() gives the total cost of the item, and this is added to the total variable.
- The for-each loop is used here because it makes the code more readable and easier to understand.
Best-suited Java courses for you
Learn Java with these high-rated online courses
Advantages of For each loop in Java
- Improves code readability and ease of understanding
- Reduces chance of errors by eliminating need for index variable
- Easy to write and use, requires less code
- Can be more efficient for large collections
- Flexible and can be used with various types of collections
- Considered a modern approach
- Enables use of functional programming with Stream API
- A good option for collection traversals.
Limitations of For each loop in Java
1. For-each loop cannot modify an array:
int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { num *= 2; // This will not modify the elements in the numbers array}
Using Traditional Approach
for (int i = 0; i < numbers.length; i++) { numbers[i] *= 2;}
2. For-each loop cannot obtain the index of an element in an array:
int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println("Element: " + num); // We can not get index of current element here}
Using Traditional Approach
for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]);}
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio