For-each loop in Java
![]() |
Image Source - Google | Image by - educba.com |
There is another type of for loop called for each loop which is introduced in Java 5, it is also called enhanced for loop which is mainly used to print the array elements and collection elements let's see what are the features of for each loop-
- It starts with the keyword for just like normal for loop followed by two parenthesis
- Instead of using the three conditions you declare a variable which is of the array type or collection type on which you are going to iterate followed by a colon, which is then followed by the array name.
- It does not print the array elements on the index basis (no concept of index)
- Inside the for loop use variable of the array type or collection type to work with.
Syntax of for each-loop
int a[] = {5,4,3,2,1};
for(int var:a)
{
//use var to print any statement;
}
Program 01-"Traverse the array using for each loop"-
public class Arrays07 {
public static void main(String[] args)
{
int a[] = {5,4,3,2,1};
for(int each:a)
{
System.out.print(each+" ");
}
}
}
Output:
public class Arrays07 {
public static void main(String[] args)
{
int a[] = {5,4,3,2,1};
for(int each:a)
{
System.out.print(each+" ");
}
}
}
5 4 3 2 1
Program 02- Print the odd numbers from 1 to 10 in the given array by using for each loop-
int a[] = {1,2,3,4,5,6,7,8,9,10}; //given array
Source code-
public class Arrays07 {
public static void main(String[] args)
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
System.out.println("the odd numbers are:");
System.out.println(); //for new line
for(int each:a)
{
if(each%2==0)
{
continue;
}
else
{
System.out.print(each+" ");
}
}
}
}
Output:
the odd numbers are:
1 3 5 7 9
Program 03- Traverse the Array-List elements(Collection type) using for-each loop-
Source code-
import java.util.*;
public class Array08 {
public static void main(String[] args)
{
ArrayList<Integer> a = new ArrayList<Integer>();//collection type
a.add(10);
a.add(20);
a.add(30);
a.add(40);
a.add(50);
System.out.println("Arraylist contains elements:"+"\n");
for(int each:a)
{
System.out.println(each+" ");
}
}
}
Output:
Arraylist contains elements:
10
20
30
40
50
Advantages of for-each loop
- It makes the code more readable
- It reduces the programming errors
- More easy way to print the array
Disadvantages of for-each loop
- It does not works on the index basis
- It cannot traverse the elements in reverse order.
Imp.note- It is recommended to use for each loop to traverse the array and collection elements .
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.