devxlogo

The Enhanced For Loop

The Enhanced For Loop

In the field of information technology, what counts more is the early adaptation of the new features that come with every new version of software. Coming up with the JDK 1.5 (tiger) release of Java is a new feature of the enhanced for loop. Let see how it works!

In the enhanced for loop, the array index is not necessary for the retrieval of an array element:

int arr[5] = {2,4,8,16,32}; for (int i=0; i<5; i++)                System.out.println("Output: " + arr[i]);

Now, you can save a few keystrokes and retrieve an array element thusly:

 for(int a:arr)                      //  check syntax, it's colon not semi-colon                 System.out.println("Output: "+ a);

The enhanced for loop also works with collection frameworks. So instead of using Iterators (which are unually used to get elements out of a collection), you can do something like this:

Vector vec = new Vector();                vec.addElement(new Integer(2));                vec.addElement(new Integer(4));                for(Object obj:vec)                                                System.out.println("Output: "+(Integer)obj);
See also  Comparing different methods of testing your Infrastructure-as-Code
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist