Arrays Enhanced for loop

Arrays Enhanced for loop

As the new Java versions are released, the coding becomes easier and Java becomes more robust language to practice, For example JDK 1.5 introduced a new for loop with which iteration of elements of arrays and data structures becomes easier. Start reading this tutorial on "Arrays Enhanced for loop".

Java for loop is modified (enhanced) to suit arrays and collections (data structures). Elsewhere for general loop requirements, this does not work. This modified for loop, known as enhanced for loop, is similar to the foreach loop of many object-based languages like JavaScript,, PHP, Delphi etc. For this, many call the enhanced for loop as foreach loop of Java. This is introduced with JDK 1.5.

Now let us see how it is simple to write. Illustrations are given with respect to the following.

1. Arrays – Arrays Enhanced for loop (foreach)
2. Collections – Collections Enhanced for loop (foreach)

1. Enhanced for loop with arrays

Observe the code on Arrays Enhanced for loop before going into the details.

Arrays Enhanced for loop
Output screenshot on Arrays Enhanced for loop

The new for loop does not have initialization, incrementing and condition checking of a traditional for loop. Then how it works? In each iteration, one element of the array is copied into the k variable. The k variable is printed in the body. Condition checking etc. are taken care of implicitly. This for loop is an instruction to the JVM just to print the elements of the array. Observe, the type of the array and variable in the for loop are of the same data type, int.

For a similar for loop with collections is available at Collections Enhanced for loop (foreach).

2 thoughts on “Arrays Enhanced for loop

  1. senthil

    Collections Enhanced for loop (foreach) redirect to concurrentException page. Looks it redirect to a not expected link

Leave a Reply

Your email address will not be published. Required fields are marked *