For Each loop in Java

Purpose:

    Understanding enhanced for loop

Program:

public class ArrayDemo
{
	public static void main(String args[])
	{
		// declare an array of size 3
		int arr[]= new int[3]; 
		// initialize array with 3 values
		arr[0]=1;
		arr[1]=2;
		arr[2]=3;
		
		//using FOR EACH loop
		for(int n:arr)
		{
			System.out.println(n); // printing array values
		}
	}
}

Explanation:
Here with help of for each loop, we retrieve array values one by one from an array, “arr” and store it in a variable “n”. This for each loop automatically retrieves value one by one, hence no need of increment operator like used in a normal for loop i.e

for(int a; a<3; a++)

Capture

Same program using normal for loop:

public class ArrayDemo
{
	public static void main(String args[])
	{
		// declare an array of size 3
		int arr[]= new int[3]; 
		// initialize array with 3 values
		arr[0]=1;
		arr[1]=2;
		arr[2]=3;
		
		//using FOR loop
		for(int n=0; n<3; n++)
		{
			System.out.println(arr[n]); 
			// printing array values
		}
	}
}

Capture

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s