Written by Sai Sandeep Thota on January 20, 2014 in Java > Programming

Enhanced For Loop in Java

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Enhanced For Loop is a for loop which is useful for scanning the elements in an array. There are many advantages like readability, clarity, you don’t need to know the current index, scanning elements from first-to-last. It is simple but doesn’t have flexibility like the traditional for loop.

Enhanced For Loop in Java

for(Data-type variable_name : array_name)

For example if you have an array named data then to scan and print the elements present in that array, the code will look like this:

for(int i : data)
{
	System.out.println(i);
}

Using the traditional for loop the code will look like:

for(int i=0;i<data.length;i++)
{
	System.out.println(data[i]);
}

So the main difference is that you will need to use the array name and the for loop’s variable to print the data whereas in the Enhanced For Loop you will just use the for loop’s variable to print the data.

Java Enhanced For Loop Example Program

import java.util.Scanner;

class enhancedForLoop {
	public static void main(String args[])
	{
		int a[] = new int[10];
		int n;
		Scanner get = new Scanner(System.in);
		System.out.println("* * * ProgrammingUnit.com * * *");
		System.out.print("Enter Number of Elements: ");
		n = get.nextInt();

		for(int i=0;i<n;i++)
		{	
			System.out.print("\nEnter "+(i+1)+" Element: ");
			a[i] = get.nextInt();
		}

		System.out.println("Data present in the Array A:");
		for(int l : a) //Syntax: for(int var_name : array_name)
		{
			System.out.print(l+"\t");
		}
	}
}	

Output:
Java Enhanced for Loop

Download Source Code

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: