Home Help Java F for-each loop in java

Related Tutorials


 
 

Share on Google+Share on Google+

for-each loop in java

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

Output : After compiling and executing the program.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 15, 2013

Related Tutorials

Discuss: for-each loop in java  

Post your Comment


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