26 Jan 2017

What is for-each loop in java..??

You know about the loop concept in java if you don't know then click me ...😎😎

Now come to the point about the for-each loop.This loop is specially designed to handle the elements of a collection . Collection is the group of  elements. You know the array part of java .we can take an array as a collection of similar elements like Integer or String etc., or a class is a collection of similar methods or a package like java.util, is a collection of classes and interfaces .


What is a collection..?

A collection represents a group of elements like integer values or objects or methods classes .Examples for collections are arrays and java.util classes (Stack, LinkedList etc. ).


How can you explain it ..!!

The for-each loop repeatedly execute a group of statements for each element of the collection. It execute as many times as there are number of elements in the collection.

Lets assume an example but first know the syntax of that loop :

Syntax:

for(var: collection) //here the var is a variable attached to a collection .
{
statements;
}


here var represents each element of the collection one by one.Suppose If a collection has 5 element then the loop will execute 5 times and the var represents these elements one by one .

Lets take an example of for-each loop:

class mobile
{public static void main(String ar[])

{
int a[]={5,35,69,96,75}; // declare an integer type array with five elements.

for(int i : a)  //use for-each loop for retrieve the elements in array
{System.out.println(i);}
}
}


Output :
5
35
69
96
75

for more examples of  for-each loop click me....😊😊


What is for loop..??                   What is while loop..??

What is do-while loop..??              What is control statement..??

What is if-else statement..??           What is switch statement..??













,

No comments:

Post a Comment