Thursday, June 25, 2009

Java 5 Language Features

a5features.html



The Java 2 Platform Standard Edition Development Kit 5.0 (JDK 5.0) is a feature release of the Java platform. It contains new features and enhancements in many functional areas.







The major Language feature enhancements are



  • Generics

  • Autoboxing/Unboxing

  • Enhanced for Loop

  • Typesafe Enums

  • Varargs

  • Static Import



Generics




Generics adds compile-time type safety to the Collections Framework and eliminates casting.




List list = new ArrayList();

list.add(new String("Test")); // store any object type



To get the data you will do

String s = (String)list.get(0); // Need explicit casting



In Java 5, we can define the datatype for what we are going to store by using generics so that explicit casting is not required.



List<String> list = new ArrayList<String>(); // here we have mentioned which datatype we are going to store.

list.add(new String(""));



If you add any other datatype to the above list object it will give compile time error

list.add(new Integer(1)); // will give compile time error.



Getting the data out
String s = list.get(0); // No explicit casting required


Autoboxing/Unboxing




It elminates monotonous routine work/overhead to convert values of primitive types to objects of the corresponding wrapper classes

and Wrappr classes to primitive data types.



double d = 100.50;

Double doubleObj = new Double(i); to Wrapper class. Explicity convertion.

double dConverted = doubleObj.doubleValue(); // to primitive data type. Explicit convertion.



In Java 5, We can convert it like this



Double doubleObj = d; //Auto boxing(primitive type to Wrapper class).

double dConverted = doubleObj // Auto Unboxing(wrapper class to primitive data type).




Enhanced for Loop


Iterating Collections with for loop (using ; ; format)was bit ugly and time consuming which involves getting the object from collection, Cast to the object's data type. It is uglier with nested loops.
List list = new ArrayList();

Person person1 = new Person();

person1.setFirstName("1First");

person1.setLastName("1Last");
list.add(person1);




Person person2 = new Person();

person2.setFirstName("2First");

person21.setLastName("2Last");

list.add(person2);






for(int i=0;i<list.size();i++)
{

Person person = (Person)list.get(i);

System.out.prinln("FirstName : "+person.getFirstName()+" Last Name : "+person.getLastName());
}



In Java 5, we can write the same code as


List<Person> persons = new ArrayList<Person>();
list.add(person1)
;
list.add(person2)



for(Person person : persons)
{

System.out.prinln("FirstName : "+person.getFirstName()+" Last Name : "+person.getLastName());

}





TypeSafe
Enums




Typesafe enums defined as set of symbolic names and values.


Previous to Java 5 any enums defined and used as below


final int MONDAY = 1;
final int TUESDAY = 2;


calculateNextDay(MONDAY)



It has following disadvantages

It is 'Not TypeSafe' - we can pass any int value in above method as calculateNextDay(2)
It has 'No namespage' - first monday can be defined as 'FIRST_MONDAY' a String prefix need to be added to identify.
It has 'No informative representation' when we print that variable. In this case, printing MONDY will print 1.
It has 'Constants need to be Compiled' when the constant value changes, we need to compile the class for the changes to take effect


with Java 5
enum DAYS{MONDAY,TUESDAY}


System.out.prinln(DAYS.MONDAY);// will print MONDAY




values (returns array of enums) and valueOf (returns value of enum for the passed in value) are the most useful method



public enum OfficeHours {



INTIME(8,30),OUTTIME(5,30),LUNCHTIME(12,30);



OfficeHours(int h,int m){

this.hh = h;

this.mm=m;

}



private int hh;

private int mm;

public int getHour() { return this.hh; }

public int getMins() { return this.mm; }



}



for(OfficeHours oHrs : OfficeHours.values()){

System.out.println(oHrs+" is "+oHrs.getHour()+" : "+oHrs.getMins());

}




The detailed explaination for Enum is availabe here


VarArgs




Before Java 5 when a set of values need to be passed to an method We should put the values in array or any collection and then pass it to a method



In Java 5 we can pass set of values in varargs format

Syntax is Datatype... name i.,e Object... arg



public static void extract(String... x){

for(String m : x){

System.out.println("The month is "+m);

}



extract("Jan","Feb","March")



more details





Static Import



with static impor we can access static members without having qualified(means without using classname)



import static org.apache.commons.lang.time.DateUtils.*; // all the static memebers can be accessed with out using class name DateUtils



System.out.println("Milliseconds per hour : "+MILLIS_PER_HOUR);// instead of DateUtils.MILLIS_PER_HOUR




References : Java 5 Features




No comments:

Post a Comment