Java 1.5 - Features
Java 1.5 - Features
Java 1.5 - Features
5, including:
GenericsProvides compiletime t!pe safet! for collections and eliminates the need for casting
ever! time !ou get an o"#ect out of Collections.
Enhanced For loop$liminates errorproneness of iterators.
Autoboxing/unboxing$liminates need of manual conversion "etween primitive t!pes %such as
double& and wrapper t!pes %such as Double&.
Typesafe enumsProvides all "enefits of the '!pesafe enum pattern.
Static import$liminates the need for using class names prior to using the static mem"er
varia"les of other classes. 'his will ma(e the code a "it neater.
Metadata)llows programmers to avoid writing "oiler plate code and gives the opportunit! for
declarative programming.
Generics
*enerics is one of the coolest features of JDK 1.5. +! introducing generics, we will have compiletime t!pe
safet! and possi"l! fewer ClassCastExceptions during run time. In JDK 1.5, !ou can declare the t!pe of o"#ects
one collection will accept,return. In JDK 1.-, creating a .ist of emplo!ee names re/uires a collection o"#ect li(e
the following statement:
List listOfEmployeeName = new ArrayList();
In JDK 1.5, !ou would use this statement:
List<String> listOfEmployeeName = new ArrayList<String>();
'he cool part is that if !ou tr! to insert something that's not a string, !ou will find out at compile time and then
!ou can fi0 the pro"lem. 1ithout generics, !ou discover such a "ug when !our customer calls and tells !ou that
the program !ou shipped crashed with a ClassCastException.
'he other cool thing is that !ou don't have to cast when !ou get an element out of the collection. 2o instead of
this t!pe of statement:
String employeeName = ((String) listOfEmployee.get(i));
It's simpl!:
String employeeName = listOfEmployee.get(i);
3asting o"#ects without (nowing the t!pe of o"#ect is not good, and more importantl!, it can fail at run time.
2uppose the user accidentall! passes in a collection that contains string "uffers rather than strings. In Listing
A, the client is re/uired to pass in a collection of strings that the compiler can't enforce.Listing B shows how
the same method loo(s with generics.
4ow it's clear from the method signature that the input collection must contain onl! strings. If the client tries to
pass in a collection of string "uffers, the program won't compile. )nd notice that the method doesn't contain
an! casts. It's one line shorter and, once !ou get used to reading generics, it's clearer too.
Enhanced For Loop
5ere's the s!nta0 for the For loop in the current version of the JDK:
void printAll(olle!tion !) "
for (#terator i = !.iterator(); i.$asNe%t(); ) "
Employee emp = (Employee)i.ne%t();
System.o&t.println(emp.getName());
'
'
4ow here's the same method with an enhanced For statement:
void printAll(olle!tion !) "
for (O()e!t o * !)
System.o&t.println((+imer+as,)o).getName());
'
In this For loop, !ou should read the 6:6 as 6in,6 so the e0ample reads 6for 7"#ect o in c6. 8ou can see this For
loop has more reada"ilit!.
Autoboxing and unboxing
In Java, we have primitive data t!pes and wrapper classes around these primitive t!pes. 9ost often
programmers need to convert one t!pe to another. 'a(e a loo( at the code snippet in Listing .
Listing C
p&(li! !lass Employee "
private stati! final #nteger -#L. = new #nteger(/);
p&(li! stati! void main(String args01) "
22!ode for adding n to an #nteger
int n=3/;
#nteger age= new #nteger(4/);
Integer ageAfterTenYear= new Integer(age.intValue +10);
'
'
4otice how mess! the innerloop code that calculates ageAfterTenYear loo(s. 4ow ta(e a loo( at the same
program rewritten with auto"o0ing, as shown in Listing !.
Listing D
p&(li! !lass Employee "
p&(li! stati! void main(String args01) "
int n=3/;
#nteger age= new #nteger(4/);
#nteger ageAfter+en5ear= age 63/;
'
'
7ne thing worth noting: Previousl!, if !ou un"o0ed 4ull, it "ecame :ero. In this code, the compiler would
automaticall! convert Integer to int and add 1; to it, then convert that "ac( to Integer.
Enhanced For Loop
5ere's the s!nta0 for the For loop in the current version of the JDK:
void printAll(olle!tion !) "
for (#terator i = !.iterator(); i.$asNe%t(); ) "
Employee emp = (Employee)i.ne%t();
System.o&t.println(emp.getName());
'
'
4ow here's the same method with an enhanced For statement:
void printAll(olle!tion !) "
for (O()e!t o * !)
System.o&t.println((+imer+as,)o).getName());
'
In this For loop, !ou should read the 6:6 as 6in,6 so the e0ample reads 6for 7"#ect o in c6. 8ou can see this For
loop has more reada"ilit!.
Typesafe enums
'!pesafe enums provide the following features:
'he! provide compiletime t!pe safet!.
'he! are o"#ects, so !ou can put them in collections.
'he! are implemented as a class, so !ou can add some methods.
'he! provide a proper name space for the enumerated t!pe.
'heir printed values are informative<if !ou print an int enum, !ou #ust see a num"er, which ma! not
"e that informative.
Example "#
en&m Season " winter7 spring7 s&mmer7 fall '
Example $#
p&(li! en&m oin "
penny(3)7 ni!,el(8)7 dime(3/)7 9&arter(:8);
oin(int val&e) " t$is.val&e = val&e; '
private final int val&e;
p&(li! int val&e() " ret&rn val&e; '
'
Static imports
2tatic imports ma(e code more reada"le. 3urrentl!, !ou use constants defined in other classes, li(e this:
import org.yyy.p,g.#n!rement;
!lass Employee "
p&(li! .o&(le !al!&lateSalary(.o&(le salary"
ret&rn salary 6 #n!rement.#N;E<EN+ = salary;
'
'
+ut with static import, we can use those constants without providing the name of the class prior to constant
name, li(e this:
import stati! org.yyy.p,g.#n!rement;
!lass Employee "
p&(li! .o&(le !al!&lateSalary(.o&(le salary"
ret&rn salary 6 #N;E<EN+ = salary;
'
'
4ote that we are a"le to call the I43=$9$4' constant without using the class name Increment.
Metadata
'he metadata feature is focused on ma(ing a developer's life simpler with the support of tools provided "!
vendors. 'a(e a loo( at the code in Listing E.
1ith metadata support, !ou can write the code in Listing E li(e this:
import org.yyy.$r;
p&(li! !lass Employee "
>;emote p&(li! String getName() "
...
'
>;emote p&(li! p&(li! String getLo!ation() "
...
'
'
)s !ou can see, all the "oilerplate's code is gone.
'he new features and specifications that will "e implemented in JDK 1.5 offer the Java programming
communit! man! more options for writing ro"ust, scala"le code. 2erious Java programmers would do well to
"egin familiari:ing themselves with the pending version of the Java programming language.