Tuesday, March 21, 2017

Java For each loop with example

In this post we will talk about for each loop in java with example. This loop has introduced in JDK 1.5 version.Java adds the for-each capability by enhancing the for statement.The for-each loop is most convenient loop to access the elements of arrays & collections and and the main advantage of for-each loop is no new keyword is required,and no preexisted code is broken.

General syntax for for-each loop:

for(type itr-var:collection)
{
Statement block;
}

In the above syntax type specifies type and itr-var specifies the name of the iteration variable that will receive the elements from the collection,one at a time,from the beginning to end. The main limitation of for-each loop is applicable for arrays & collections only. But there is no limit for general for loop.

How for-each loop works:


Example:

class Books
{
public static void main(String args[])
{
String names[]={"java","SQL","Spring"};
for(String name:names)
{
System.out.println(name);
}
}
}

Output:






In the above program, when the first iteration, this name variable contain first element name as java of the names[] array variable.The second iteration contains the second element SQL of the name[] array variable,similarly this loop repeats all the elements until all the collections have been obtained. All the elements have been passed in the name variable,finally that name variable display as output(result).

With each pass through a loop name variable automatically given a value equal to the  next element in names. Thus in the first iteration name variable contains java  , and 2nd iteration contains name contains SQL and so on.

See also:

Java exception Handling programs
How to find duplicate elements in array
How Java program works internally?
Why String immutable in java


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...