What is For each loop in Java?


For each loop in java, also known as the enhanced for loop was introduced in the Java 5.0. Just like other loops, for each loop is also another array traversing technique. But it has some advantages and some disadvantages over for loop.
Let us look at some advantages first.

Advantages

  • The possibility of programming error is eliminated.
  • It makes the code more readable.
  • There is no use of index or rather a counter in this loop.

Now let us have a glance at some of its disadvantages.

Disadvantages

  • It cannot traverse through the elements in reverse fashion.
  • You cannot skip any element as the concept of index is not there.
  • You cannot choose to traverse to odd or even indexed elements too.

Syntax

Let us have a look at the syntax of for-each loop.


It starts with the for keyword similar to a for loop. Now, instead of declaring and initializing a loop counter variable, you simply declare a variable followed by a colon, which is then followed by the array name.
Coming to the body of the loop, you can use the variable you created rather than using an indexed array element.

Example

Let us look at a simple example in order to understand for-each loop.


Output

Let us look at the output of the above example code.

For each Loop in Java
Fig.1- For each Loop in Java

Here the variable x moves from one element to the other while executing the body of the loop. The name for-each was derived from its behaviour to traverse each element one by one.
It is commonly used to iterate over an array or a Collection class such as ArrayList. Let us look at an example of for-each loop for ArrayList.


Output

Let us look at the output of the above example code.

For each Loop in Java for ArrayList
Fig.2- For each Loop in Java for ArrayList

Summary

When accessing collections, a for-each loop is significantly faster than a for loop for array`s access. Since, for each loops helps in making the code more readable, it is recommended to use for each loop for traversing the elements of an array. The drawbacks should also be taken into consideration and as per the need, the type of loop required can be selected.

Read More

Author : Satyam Kumar -



You will also like: