If you want to go through data without having to deal with things like i++ or array.length-1, the Java for-each loop is what you need. The enhanced for loop, added in Java 5, is about Java data, not how to access it. This article is going to show you how the system works. The system is better for some tasks. You will learn why the system is better for these tasks. This will also teach you how to use the system.
What is the Java For-Each Loop?
The Java for-each loop is really handy for going through all the elements in an array or a collection. It does this without using a variable like you do in a regular loop. The Java for-each loop just goes through each element one at a time.
The Java for-each loop is excellent when you don’t need to know your exact position in the list. You just want to do something with each element. The Java for-each loop makes your code easier to understand. You have to write a lot less code to get things done.
Java For-Each Loop Syntax
Understanding the Java for-each loop syntax is the first step toward writing cleaner code. It uses the ‘for’ keyword but follows a different internal structure compared to the classic version.
The basic structure looks like this:
Java
for (type variableName : arrayName) {
// Code block to be executed
}
Breaking down the components:
- Type: The data type of the elements in the array or collection (e.g., int, String, or a custom Object).
- variableName: A temporary name given to the current element being processed in the current iteration.
- Colon (:): This acts as the separator, which you can read as “in”.
- arrayName: The name of the array or collection you want to loop through.
Java For-Each Loop Examples
Let’s look at a Java for-each loop example to see how it works in a real situation. Imagine you have a list of student names from a school. You want to print each student name. In Java, a for-each loop is useful here.
Traditional loop approach:
Java
String[] students = {“Amit”, “Sneha”, “Rahul”};
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
Java For-Each Loop approach:
Java
String[] students = {“Amit”, “Sneha”, “Rahul”};
for (String name : students) {
System.out.println(name);
}
In the second example, you don’t have to worry about the index i. The loop automatically knows to start at the first name and stop after the last one.
Java For-Each Loop Array
When you use a Java for-each loop array, things are basic. You can have an array of integers, doubles or characters, and the Java for-each loop takes care of going through each one for you. The Java for-each loop does all the work of moving from one thing to the next, inside the array.
Here is a Java for-each loop program that calculates the total sum of an integer array:
Java
public class SumArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println(“Total Sum: “ + sum);
}
}
In this case, the Java for-each loop array logic ensures that every single number in the set is added to the sum without the risk of skipping an index or going past the array bounds.
Java For-Each Loop vs For Loop
Choosing between a standard for loop and the enhanced version depends on your specific needs. Here is a quick breakdown of the Java for-each loop vs for loop logic:
| Feature | Traditional For Loop | Java For-Each Loop |
| Index Access | Has access to the index (i) | No direct access to the index |
| Modification | Can modify array elements | You cannot directly modify elements using the loop variable itself |
| Direction | Can go forward, backward, or skip | Forward only, one by one |
| Readability | More complex syntax | Clean and easy to read |
| Risk | High risk of “Off-by-one” errors | Almost zero risk of index errors |
Use the traditional loop if you need to update values at a specific position or if you need to loop backwards. Use the Java for-each loop if you simply need to read or process every item in a list.
Java For-Each Loop List
The power of this loop really shines when using the Java for-each loop list functionality. When you work with the Collections Framework (like ArrayList or LinkedList), the for-each loop makes traversal incredibly simple.
Example with ArrayList:
Java
import java.util.*;
public class ListExample {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add(“Delhi”);
cities.add(“Mumbai”);
cities.add(“Bangalore”);
for (String city : cities) {
System.out.println(“Welcome to “ + city);
}
}
}
This approach is much cleaner than using an iterator or a manual counter, especially as the size of your data grows.
Java For-Each Loop Nested
You can also use a Java for-each loop nested structure to handle multidimensional arrays or lists within lists. This is common in Data Structures and Algorithms (DSA) when dealing with grids or matrices.
Example of a 2D Array:
Java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + ” “);
}
System.out.println();
}
In this Java for-each loop nested example, the outer loop picks up each individual array (the rows), and the inner loop iterates through the integers within those rows.
Things to Keep in Mind for Java For-Each Loop
While the for-each loop is convenient, it isn’t always the right tool.
- No Reverse Iteration: You cannot use this loop to go from the end of a list to the beginning.
- No Index Knowledge: If you need to know which position you are at (for example, to print “Item 1, Item 2”), you’ll need to manually maintain a counter.
- Single Element Access: You cannot compare two elements side-by-side (like arr[i] and arr[i+1]) easily.
- No Modification: You cannot change the value of the elements inside the loop. If you try to assign a new value to the temporary variable, the original array remains unchanged.
Also Read :
- Java Logical Operators
- Concatenate String In Java
- Java Short Hand If..Else (Java Ternary Operator)
- Java Assignment Operators
- Java Boolean Data Types
- Java Arithmetic Operators
- Java Nested If Statements
- Java Numbers
FAQs
Can I use the Java for-each loop to remove items from a list?
When you try to remove things from a list while you are going through it with a Java for-each loop, it will probably give you a ConcurrentModificationException. So what you should do is use an iterator when you need to remove things from the list.
How do I obtain the index in a Java for-each loop?
When you are using the Java for-each loop, it does not provide you the index. The Java for-each loop doesn't do that, so you need to find another way to track the index. To do this operation with the Java for-each loop, you need to declare an integer outside of it.
Can I use the Java for-each loop for a 2D array?
Yes, you can use a Java for-each loop nested approach. The first loop iterates through the rows (which are arrays), and the second loop iterates through the individual elements.
What happens if the array is null?
If you try to run a Java for-each loop program on a null reference, the JVM will throw a NullPointerException. Always verify that your array or collection is initialised before looping.
