In Java, both for loop and for-each loop are used for iterating over arrays or collections, however they have different syntax and their usage is also different. In this guide, we will discuss the difference between for loop and for-each loop with the help of examples. I have covered these loops separately here: for loop and for-each loop.
for Loop
Syntax:
for (initialization; condition; increment/decrement) {
// code that needs to be executed repeatedly
}
Characteristics:
There are three main parts of a traditional for loop, these are:
- Initialization: This part executes once when the loop starts. It usually initialises the loop counter variable.
- Condition: This part of the loop is evaluated for each iteration, if it returns true, the loop continues else the loop stops.
- Increment/Decrement: This part of the loop executes at the end of the iteration, it usually updates the counter variable. This is important as it ensures how many time a loop has to run, if it doesn’t update the counter variable the condition remains true for infinite times.
Use Cases:
- The traditional for loop is suitable when you need to iterate over a specific number of times.
- Useful when you need to access the loop counter variable.
Example:
Let’s see the examples to understand how a for loop is used to iterate over arrays and collections.
Iterating Over an Array using for Loop
public class ForLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Using a for loop to iterate over the array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Item at index " + i + ": " + numbers[i]);
}
}
}
Iterating Over a List using for Loop
import java.util.ArrayList;
import java.util.List;
public class ForLoopListExample {
public static void main(String[] args) {
// A list of names
List<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");
// Using a for loop to iterate over the list
for (int i = 0; i < names.size(); i++) {
System.out.println("Item at index " + i + ": " + names.get(i));
}
}
}
for-each Loop (Enhanced for
Loop)
Syntax:
for (Type element : collection) {
// code that needs to be executed
}
Characteristics:
- The for-each loop is easier to write and more readable than traditional for loop.
- It doesn’t require loop counter variables.
- It provides read-only access to the array or collection during iteration.
- The loop variable
element
represents the current element directly, which makes the code type safe and more readable.
Use Cases:
- It is suitable when you do not need to know the loop counter variable value during each iteration.
- Always advisable to use for-each loop, when you need to iterate over all elements of a collection or array.
Example:
Iterating Over an Array using for-each Loop
public class ForEachLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Using a for-each loop to iterate over the array
for (int number : numbers) {
System.out.println("Item: " + number);
}
}
}
Iterating Over a List using for-each Loop
import java.util.ArrayList;
import java.util.List;
public class ForEachLoopListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");
// Using a for-each loop to iterate over a list
for (String name : names) {
System.out.println("Item: " + name);
}
}
}
Comparison between for and for-each
- Flexibility:
for
loop: More flexible as it gives you access to loop counter.for-each
loop: Less flexible, suitable when you need to iterate all the elements.
- Access to Index:
for
loop: You can access loop index, which is nothing but the loop counter variable value during each iteration.for-each
loop: Doesn’t give you access to loop index as it doesn’t have any.
- Modifying the Collection or Array:
for
loop: You can modify the element during iteration.for-each
loop: You cannot modify array or collection during iteration.
- Performance:
- Both loops give almost similar performance.
- Less prone to error:
- The syntax of for-each is simple and more readable, thus it is less prone to human error compared to traditional for loop.
Leave a Reply