for-each loop in java

This tutorial will help you to find how for-each loop works.

for-each loop in java

In this section you will learn about for-each loop in java. for-each is a control statement which is used to traverse an array or object. for-each loop is used to iterate over array or collection object as well. for-each loop is also known enhanced for loop.

Syntax :  for(data-type variable_name:array-name)

 Let us suppose, we declare and initialize an array having five elements, then for-each loop is used for traversing array and displaying the element of array.

Advantage of for-each loop:

  • The for-each loop increase the readability of program.
  • It reduces the chances of error in the program.

Disadvantage of for-each loop:

  • The for-each loop is not used when you try to replace element in a list or array while traversing.
  • for-each loop is not used while traversing over multiple collection in parallel.
  • for-each loop is not used for filtering.

Example :  A program using for-each loop

public class Foreach {

	public static void main(String args[])
		int[] a={10,20,30,40,50};
		for(int x:a)

Output : After compiling and executing the program.