What are the new features came in java1.5 ?

In java5 some new features came,
Such as
- Generics
Problem: Collection element types
Cannot be checked at compile time
Assignment must use cast
Can cause runtime errors( ClassCastException)
Tell the compiler what type your collection is
Compiler can fill in casts for you
Guaranteed to succeed *
Old code
List l = new LinkedList();
l.add(new Integer(0));
Integer i = (Integer)l.iterator.next();
New code
List l = new LinkedList();
l.add(new Integer(0));
Integer i = l.iterator.next();
- Enhanced for loop (“foreach”)
Iterating over collections is tricky
Often, iterator only used to get an element
Iterator is error prone (Occurs three times
in a for loop)
Can produce subtle runtime errors
Solution: Let the compiler do it
New for loop syntax
for (variable : collection)
Old code
void cancelAll(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask task = (TimerTask)i.next();
task.cancel(); } }
New Code
void cancelAll(Collection c) {
for (TimerTask task : c)
Also works for arrays
- Autoboxing/Unboxing
Conversion between primitive types and wrapper objects (and vice-versa)
Needed when adding primitives to a collection
Solution: Let the compiler do it
Integer intObj = 22; // Boxing conversion
int i = (int)intObj // Unboxing conversion
ArrayList al = new ArrayList();
al.add(22); // Boxing conversion
- Type-safe enumerations
Variable needs to hold limited set of values
e.g. Card suit can only be Spade, Diamond, Club, Heart
Solution: New type of class declaration
enum type has public, self-typed members for each enum constant new keyword, enum
works with switch statement
- Varargs
To have a method that takes a variable number of parameters
Can be done with an array, but not nice
Look at java.text.MessageFormat
Solution: Let the compiler do it for you
New syntax:
public static String format(String fmt,
Object... args);
- Static import
Having to fully qualify every static referenced from external classes
Solution: New import syntax
import static TypeName . Identifier ;
import static Typename . * ;
Also works for static methods and enums
e.g Math.sin(x) becomes sin(x)
- Metadata
Some APIs require lots of standard code
How to indicate this to a tool
Solution: Annotated source code
@remote getPrice(Product p)

Concurrency Utilities
Goal: Beat C performance in high end
server side applications
New framework for locks to provide greater flexibility over synchronized
No more threads, use Executors
Use anExecutor.execute(aRunnable)
Not new Thread(aRunnable).start();
Runnable and Callable
Callable for things that return values and/or exceptions

No comments:

Post a Comment