For each loop in Java

For each loop in Java

2 mins read224 Views Comment
clickHere
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 11, 2023 16:56 IST

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.

2022_02_j.jpg

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 integers
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
Copy code

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.

How to Find Reverse of a Number in Java
How to Find Reverse of a Number in Java
Reversing a number in Java is a common task that can be accomplished using a variety of methods. For example, you can use a loop to iterate over the digits...read more
Check Palindrome in Java Using Different Methods
Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation,...read more
Fibonacci Series in Java [Case-Study Based]
Fibonacci Series in Java [Case-Study Based]
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, the Fibonacci...read more

Here’s another example,

 
//for-each loop that iterates through a List of Strings
List<String> list = Arrays.asList("A","B","C","D");
for(String str : list) {
System.out.println(str);
}
Copy code

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;
}
}
Copy code
  • 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.
Swapping of Two Numbers in Java
Swapping of Two Numbers in Java
Get an introduction to swapping the values of two numbers in Java using different methods. Compare the use of a temporary variable, arithmetic operators, and bitwise operators for swapping numbers.
How to Check Leap Year in Java?
How to Check Leap Year in Java?
In this blog, you will learn how to check leap year in Java. A leap year is a year that is divisible by 4 and 400 but not by 100....read more
Switch Case in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more

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
}
Copy code

Using Traditional Approach

 
for (int i = 0; i < numbers.length; i++) {
numbers[i] *= 2;
}
Copy code

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
}
Copy code

Using Traditional Approach

 
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
Copy code

About the Author
author-image
Atul Harsha
Senior Manager Content

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