Java J2EE Portal
Enterprise Java Station
J2EE curve
Java News / Articles
Java News / Articles
Integrating BPEL, Human Workflow and Business Rules in Java EE
Offline Ajax Applications Using Google Gears
Introduction to Rich Internet Applications (RIAs) and Adobe Flex
Processing...
Buy Java, Deals On Software Technology Store
Click here for great deals on computers, laptops, software and books
What's new in J2SE 5.0? Part 2: Enhanced For Loop and Auto-boxing / Unboxing PDF Print
Written by Chinmay Ogale   
Jan 03, 2005 at 05:32 PM

In part one of this series of articles, we had a look at generics and how they can make a difference to the way you code Java.

In this second part, I will cover two major features introduced in J2SE 5.0 , ?Enhanced For Loop? and ?Autoboxing/Unboxing ?.Let?s start with the enhanced for Loop.

Enhanced For Loop

First of all, have a look at the traditional approach of writing a for loop to iterate over the arrays/collections. Then we can understand why the new for loop is termed as Enhanced.

Listing 1

List mylist = new ArrayList(); 
mylist.add(new Integer(10)); 
mylist.add(new Integer(99)); 
for (int i=0; i < myList.size(); i++) { 
  Integer mynum = (Integer)mylist.get(i); 
  System.out.println("mynum>> " + mynum); 
} 

In the above code we can see that to iterate over an Arraylist we use an Iterator. to iterate over mylist.

Then in for loop we cast each object from mylist into an Integer

New Approach:

Listing 2

List mylist = new ArrayList(); 
mylist.add(new Integer(10)); 
mylist.add(new Integer(99)); 
for(Integer mynum:mylist) { 
  System.out.println("mynum>>"+mynum); 
}

Listing 2 shows the new changed syntax of for loop. In the above code ArrayList has been defined and two elements have been added to it. In blue note the new for loop.




Add This Feed Button

Enter your Email


Java Expert Interviews
Sameer Tyagi Sun
Understanding Web Services and SOA
Open-Source keeps me 'coding fit'
Bruce Johnson
Google Web Toolkit isn't just another way to create mediocre Ajax applications
Processing...
Go to top of page  Home |
SiteMap

Copyright 2004 to 2008 Rightrix Solutions. All rights reserved. All product names are trademarks of their respective companies. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Rightrix Solutions and IndicThreads.com are independent of Sun Microsystems, Inc.

Views expressed at IndicThreads.com reflect the views of the authors alone, and do not necessarily reflect those of IndicThreads.com. IndicThreads.com and it's authors are not responsible for reader comments and opinions.

Enterprise Java J2EE JEE Portal >> IndicThreads.com