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, vb.net, 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.
public class ForEachArrays
{
  public static void main(String args[])
  {			// illustration with int array
    int marks[] = { 40, 50, 60, 70, 80 };
  
   System.out.print("Printing int array with taditional for loop: ");
   for(int i = 0 ; i < marks.length; i++)
   {
     System.out.print(marks[i] + "  ");
   }

   System.out.print("\nPrinting int array with enhanced for loop: ");
   for(int k : marks)
   {
     System.out.print(k + "  " );
   }
			// illustration with string array
   String names[] = { "S N Rao", "Sumathi", "Sridhar", "Jyothi", "Jyostna" };
  
   System.out.print("\n\nPrinting string array with taditional for loop: ");
   for(int i = 0 ; i < names.length; i++)
   {
     System.out.print(names[i] + "  ");
   }

   System.out.print("Printing string array with enhanced for loop: ");
   for(String str : names)
   {
     System.out.print(str + "  " );
   }
  }
}


Arrays Enhanced for loop
Output screenshot on Arrays Enhanced for loop

       for(int k : marks)
       {
         System.out.print(k + "  " );
       }

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. Collections Enhanced for loop (foreach) redirect to concurrentException page. Looks it redirect to a not expected link

Leave a Comment

Your email address will not be published.