Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

for-each loop in java

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

Ads

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)
		{
			System.out.println(x);
		}
	}
}

Output : After compiling and executing the program.

Advertisements

Share on Google+Share on Google+

for-each loop in java

Posted on: June 15, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: for-each loop in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads