Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

for each loop

  1. It is also called as enhanced for loop introduced in 1.5 version.
  2. It is a specially designed loop to retrieve all data items from arrays and collections.
Example:1
int[]  a = {
	10,
	20,
	30,
	40,
	50
};
now we will retrieve elements from this array using normal
for loop and using
for each loop:
	using normal
for loop:
	for (int i = 0; i < a.length; i++) {   
		System.out.println(a[i]);
	}
Using
for each(enhanced
	for) loop
for (int a1: a) {    
	System.out.println(a1);
}
Example-2:
Assume we have a 2 dimensional array like,
int[][]  a = {
	{
		10,
		20,
		30
	},
	{
		40,
		50
	}
};
now we will retrieve elements using normal
for loop and using enhanced
for loop:
Using normal for loop:
for (int i = 0; i < a.length; i++) {
	for (j = 0; j < a[i].length; j++) {
		System.out.println(a[i][j]);
	}
}
Using
for each(enhanced
	for) loop
for (int[] a1: a) {
	for (int a2: a1) {
		System.out.println(a2);
	}
}
Advantage

For each loop is the best choice to retrieve data items from arrays and collections. Disadvantages It is not a general purpose loop.

For Example:

 for(int i=1;i<5;i++)
{
System.out.println(“SILAN SOFTWARE”);
}
Here we can’t write an equivalent code using for each loop directly.
By using normal for loop, we can print array elements either in original order or in reverse order, but by using for each loop we can print array elements only in original order but not in reverse order.
Example,
int[] a={10,20,30,40,50};
for(int i=a.length-1;i>=0;i--)
{
System.out.println(a[i]);
}

Here we can’t write an equivalent code using for each loop. So this is also a disadvantage point.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext