by Dinesh Thakur Category: array

With the release of version 1.5, Java introduced a new type of for loop known as enhanced or numerical for loop. It is designed to simplify loops that process elements of array or collection. It is useful when you want to access all the elements of an array but if you want to process only part of the array or modify the values in the array then use the simple for loop.

When used with an array, the enhanced for loop has the following syntax,

for (type itr_var : arrayName)

{ statement(s) }

where type identifies the type of elements in the array and itr_var provides a name for the iteration variable that is used to access each element of the array, one at a time from beginning to end. This variable will be available within the for block and its value will be the same as the current array element. The arrayName is the array through which to iterate. For example:

for (int i : num)


This enhanced for loop header specifies that for each iteration, assign the next element of

the array to int type variable i and then execute the statement. During the first loop iteration, the value contained in num[0] is assigned to i which is then displayed using the println () method. After completion of the first iteration, in the next iteration, the value contained in num[1] is assigned to i which is then displayed using println ()method. This process continues until the last element of the array is processed.

public class EnhancedForLoop

       public static void main(String[] args)
          int[] num = {5,15,25,30,50};
          System.out.println("Display Elements Using Numeric for Loop : ");
              for(int i=0;i<num.length;i++)
                   System.out.print(num[i]+" ");
         System.out.println("\nDispay Elemnts Using Enhanced for Loop : ");
              for(int i : num)
                   System.out.print(i +" ");

Enhanced For Loop in Java with Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content

Popular Article