For Each Loop in Java
The for each loop in Java, also known as the enhanced for loop, is used to iterate through elements of arrays and collections easily.
Unlike the traditional for loop, the for each loop does not require initialization, condition, or increment/decrement statements. It automatically moves through each element of a collection or array.
What is For Each Loop in Java?
A for each loop in Java is a simplified version of the traditional for loop that is specially designed for traversing arrays and collections.
It executes a block of code once for each element present in the array or collection.
Syntax of For Each Loop in Java
for(dataType variable : arrayName) {
// code to execute
}
How For Each Loop Works in Java?
- The loop starts from the first element of the array or collection.
- Each element is assigned to the loop variable one by one.
- The code block executes for every element.
- The loop automatically stops after processing all elements.
Example of For Each Loop in Java
public class Main {
public static void main(String[] args) {
int numbers[] = {10, 20, 30, 40};
for(int number : numbers) {
System.out.println(number);
}
}
}
20
30
40
For Each Loop with String Array
The for each loop can also be used to access elements of a String array without using indexes.
public class Main {
public static void main(String[] args) {
String names[] = {"John, Alex, David};"
for (String name : names) {
System.out.println(name);
}
}
}
Alex
David
For Loop vs For Each Loop in Java
- For Loop: Used when you need control over index, starting point, and ending point.
- For Each Loop: Used for simple traversal of arrays and collections.
- For each loop does not provide direct access to the index value.
Advantages of For Each Loop in Java
Simple Syntax
Requires less code compared to traditional for loops.
Easy Traversal
Makes reading array and collection elements easier.
Less Errors
Reduces chances of index-related errors.
Limitations of For Each Loop
- Cannot access the index position directly.
- Cannot easily modify elements while iterating.
- Not suitable when you need custom iteration control.