Let’s learn for-each loop in java.
For-each loop in java
For-each loop traverses each element of an array sequentially without using index or counter. for-each loop or enhanced for loop was introduced in Java 1.5 version. Here’s the syntax and example on for each loop.
Syntax:
for(<DataType of array><variablename> : <Array to be iterated>) { // code }
Example:
public class ForEachLoopExample { public static void main(String[] args) { int[] numbers = {2, 4, 6, 8, 10}; // for each loop for(int n : numbers) { System.out.println(n); } } }
Output:
2
4
6
8
10
NOTE:
- Iterating through characters in a string using for-each loop is forward only and in single step.
- For-each loop is not suitable when you want to modify an array.
- In for-each loop we cannot process two decision making statements at one time like if else statement.
- For-each loop can’t keep track of index.
- For-each loop is basically used to traverse elements in Arrays and Collections.
Disadvantage of for each loop
- for-each loop is only applicable for Arrays and Collections.
- Using for-each loop we can print array elements only in original order but not in reverse order.
Traversing or iterating array using for each in java
Let’s iterate array using for each in java.
public class ForEachArrayExample { public static void main(String[] args) { String[] strColors = {"red", "blue", "green", "orange", "violet"}; // using for loop System.out.println("Using conventional for loop: "); for(int a = 0; a < strColors.length; a++) { System.out.println(strColors[a]); } System.out.println("\nUsing foreach loop: "); // using for-each loop for(String str : strColors) { System.out.println(str); } } }
Output:
Using conventional for loop:
red
blue
green
orange
violet
Using foreach loop:
red
blue
green
orange
violet
Also read – ArrayList in java