Java 5


New Features in Java 5 - From Programmer’s Point of View
With emergence of Java 5, a set of new features is included in Java technology. Many programmers working on Java technology were excited before its release about its new features. In this article, new features of Java 5 are summarized which are important from programmer’s point of view.

Sponsored Links

Language Features
Get Rid of ClassCastException With Generics

It is very common experience among programmers to face ClassCastException at run time while integrating different parts (modules) of application which are interacting with each other in form of collections where collections are passed as parameters to methods or returned from methods or set and get in a common place holder mechanism like session. To avoid this scenario Generics are introduced in Java 5. Here is one example how to use Generics with collection classes.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* Note that there is no need to cast the object to Integer class any more*/;;
void userOfCollection(Collection pInt) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Iterator< Integer > i = pInt.iterator(); i.hasNext(); ) ;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Generic is most important and quite hyped feature of Java 5. Prior to this, there was no way to know which type of object is residing there in the collection. Generic helps programmers to integrate their stuff with each other in a declarative manner.

New Convenient for Loop

The “for” loop in Java language has been enhanced to iterate through collections. Here is the example how it works with collections.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/*Old way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void oldForLoop(Collection c) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Iterator< Integer > i = c.iterator(); i.hasNext(); );;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}..........;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* New way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void newForLoop(Collection c) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Integer i : c);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}.....;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

If you notice here, to iterate through a collection using a “for” loop has been very simple now. Prior to this, most time Iterator and Enumerator classes were used to iterate through collection objects. And in most implementations people need to iterate through collection objects.

This new implementation also helps in avoiding NoSuchElementException at run time. It also makes the code more readable and maintainable.

Autoboxing of Primitives

In the example we have discussed in the previous topic, we did something which is not required in Java 5

if(i.next.intValue() == 4)

Here in this assertion, we have to take primitive int type value from the Integer type object using intValue() method. Even to store any primitive value such as int or long in a collection object one needs to wrap it in wrapper class first and store it.

This overhead is no more required in Java 5. With autoboxing, wrapper objects can directly act as primitive type values as and when required. So we can write the above assertion statement this way also.

if(i.next == 4)

The same mechanism can be used to place primitive values in collections without wrapping them in wrapper classes.

Introduction of Enums

Type safe enum was long awaited feature in Java language. It has been introduced in Java 5.

To represent a constant custom type there was no way except definition String or int constant literals like

public static final String DAY_MONDAY = “Monday”;
public static final String DAY_TUESDAY = “Tuesday”;

But now with the introduction of enums in Java, there is a type safe and standard mechanism of defining custom types for multiple values.

Example:

enum DAY { MONDAY, TUESDAY }

This way, Monday and Tuesday are no longer String literals and also String operations cannot be performed on them (which are actually not required).

Varying Arguments – Varargs

Varargs is another step towards Java community’s commitment for object orientation and convenience of programming. We know that when we need to pass multiple values to a method as parameter, array of values (or objects) is efficient and convenient way. But, with the introduction of Varargs it has been more convenient to pass arrays or set of arguments to methods.

E.g. If a method is defined like

void doSomeThing(String[] args){}

As a client to call this method, one has to first create an array containing Strings and then call the method with that array of string as argument.

doSomeThing({“A”,”B”,”C”});

But, with varargs

void doSomeThing(String… args){}

This method can be called in two different ways.

doSomeThing({“A”,”B”,”C”});

or

doSomeThing(“A”,”B”,”C”);

Here String… in method declaration indicates that at a placeholder here either an array of String should be passed or String literals can directly be passed.But it is not advisable to override a method with vararg because it may lead confusion while calling.

Avoid Using Constant Interface Antipattern

Prior to Java 5, there was an ugly approach in using constant values named as Constant Interface Antipattern. To keep constants at one place and make them accessible in different classes of the application, it was a custom to define an interface containing all constants, other classes had to implement the interface wherever those constants were required. Actually this approach conflicts with the object orientation of Java language. Such constants are implementation details for a class but if the class accesses them by implementing an interface they become a part of public access (API) of the class. It means implementation details are being linked as API here.

To avoid this behavior, Constant Imports are introduced in Java 5. Using constant imports one can avoid implementing such interfaces.

E.g. import static com.mycompany.MyClass.MyConstant;

This constant can then be used without class qualificationint l = 5* MyConstant;

Enhancements in Libraries
Language and Utility (lang and util packages)

ProcessBuilder: Introduced as enhancement to be used in place of Runtime.exec method. It offers more flexibility.
Formatter: This new class has been introduced to improve formatting facility in Java language for String, Date, Time, and Number etc.
Scanner: This new class is based in regex implementation. It can be used to read and search from streams for a particular pattern or into a particular primitive type or String.
Networking

Ipv6 on Windows Xp and 2003 server is supported.
Timeout can be enabled and customized for any connection.
InetAdderess API has been improved in a way that it can be used to verify if host is reachable or not.
CookieHandler API has been introduced for better handling of cookies.
I18N (Internationalization)

Unicode Standard Versions 4.0 now forms basis for character handling.
DecimalFormat class has been improved in a way that precision is not lost while parsing BigDecimal and BigInteger values.
New language support: Vietnamese
Enhancements in Integration Libraries
Java Naming and Directory Interface (JNDI)

NameClassPair has been improved to access full name from directory or service.
More standard LDAP controls are being supported now e.g. Manage Referral Control, Paged Results Control and Sort Control
Improved functionality to modify LDAP names
JDBC

Five new implementation of RowSet interface has been provided with Java 5.

Straightforward implementation of RowSet functionality is JdbcRowSet.
CachedRowSet is a lightweight implementation in a way that it dose not hold connection to the data source all time. Once any operation is performed on the data source, it ends the connection and caches data offline.
Another implementation of CachedRowSet is FilteredRowSet. This can be used to derive subset of data from cached data of CachedRowSet.
JoinRowSet is also one of implementations of CachedRowSet. It can be used to derive data from multiple RowSets based on a SQL join.
To describe XML data in tabular format using standard XML schema, WebRowSet has been implemented. It is also extending CachedRowSet.
RMI

Stub classes can be generated dynamically in Java 5. With introduction of dynamic stub class generation, one does not need to run rmic compiler to generate stub classes for RMI applications. But, to be prior versions compliance, still one has option to run rmic for older version clients.
Standard APIs for SSL and TLS has been added to standard RMI library. So now RMI applications can communicate over secured Socket Layer or Transport Layer Security.

1.1 JAVATM LANGUAGE FEATURES

For more information see New Language Features.

Generics

This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Refer to JSR 14.

Enhanced for Loop

This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays. Refer to JSR 201 .

Autoboxing/Unboxing

This facility eliminates the drudgery of manual conversion between primitive types (such as int) and wrapper types (such as Integer). Refer to JSR 201 .

Typesafe Enums

This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity and the error-proneness. Refer to JSR 201.

Varargs

This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists. Refer to JSR 201.

Static Import

This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern." Refer to JSR 201.

Metadata (Annotations)

This language feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining "side files" that must be kept up to date with changes in source files. Instead the information can be maintained in the source file. Refer to JSR 175.