Wednesday, October 1, 2008

New Features Of java 1.5 from Programmer Point Of View

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.

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<> 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<> 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.

Features of java 1.5 From Mangers Point Of View

New Features In Java 5.0 - From Managers Point of View

The much awaited Java 5 has been launched in recent past by Sun. People who are in IT or related to IT industry were interested about its consequences on many factors. People who are developing applications using Java as a developing technology were more interested in new language features and other technological enhancements. But others for whom it is important to manage such process from higher level were more interested in things that are going to change with Java 5. 
In this article we are going to discuss enhancements in Java 5 over prior versions that are important from management’s point of view. 

Virtual Machine Improvements

Class Data Sharing

Class data sharing is new technique introduced to improve performance of JVM at run time. At run time of Java applications it loads system Jar file classes in a shared archive file, which are mapped with the memory. This helps JVM to improve its performance in two ways. One, loading classes at run time does not take much time, as they are already loaded in the archive, which is mapped with the memory. Also this architecture makes easy to share calluses among multiple JVMs. 
So, from management’s point of view, Java applications will now run faster with Java 5 using class data sharing technique.

Improvements in Garbage Collection Algorithm

Improvements made in garbage collection algorithm and the process is aimed to make garbage collection more customizable and controlled by the application developer or the end user of any Java application. Both initial heap size and maximum heap size are increased to avoid memory crashes in large Java applications. Maximum heap size can be in GB now. The new parallel garbage collector allows user to set time limit and space-limit to read from heap size. The user or developers to avoid out-of-memory exception can increase these limits. 
Thus, now architect and designer of the system has more control over garbage collection process in Java applications. They can configure it such a way that is scaled to achieve desired performance for the application.

Difference of Server Class Machine

Java community is already aware that the Java HotSpot JVM for server is developed and designed specially for server type machines to utilize special features of such machines and achieve best performance for the application. Here architects have got more control over usage of Java HotSpot JVM either server implementation or client. 
At the startup of any Java application, it can be configured to use Java HotSpot server JVM to run the application if the underlying machine is detected to be a server machine. At run time it can detect if the machine is a server machine or simple desktop client. Based on configuration of the hardware and performance abilities, the application itself will choose suitable JVM for it.

Small Things

Other two significant enhancements in JVM with Java 5 are improved fatal error handling and new method added to System class named as nanoTime(). This method will provide access to nanosecond timings. But the result of this function will be dependent on operating system and hardware implementation like other date-time functions.

Changing the Mask (UI)

Java 2d is enhanced to take advantage of fonts installed on the operating system to render characters in multiple languages. The advantage of this improvement is, now there are ways to display characters of multiple languages at the same time provided supporting fonts are installed on the hosting operation system. JVM can detects fonts installed in various standard directories of operating system and load them as logical fonts. 
Moreover AWT makes use of Unicode standards to display components on Windows XP and 2000 server. fonts cab are now rendered without limitations of Windows operating system.

Sound

Improvements in Java Sound technology are as listed here.

  • Sound ports are now supported on all major platforms.
    .
  • MIDI devices are supported on all major platforms.
    .
  • The new direct audio access is implemented for all major platforms. This is optimizing to use native mixers.
    .
  • Improved real time sequencer is implemented which supports all MIDI devices.
    .
  • Sound characteristics of a Java application can be configurable using properties files.
    .
  • JVM can be aborted in the middle of execution even if Java Sound is used for the application, which was not possible in prior releases.
    .
  • MidiDevices class can query all connected Receivers and Transmitters.

Improved 2D

A number of enhancements are achieved in Java 2D with launch of Java 5. Some of them are listed here.

  • Images rendered using BufferedImages are being cached now in video memory or on the server from where stream is being hosted. So now BufferedImages are also included in list of managed images by JVM and this way performance of entire application will improve.
    .
  • Java 5 offers better control over hardware to accelerate images through hardware. The developer can now set priority of the image to be rendered on hardware. Also now GraphicsConfiguration classs allows rendering transparent images.
    .
  • Java 5 supports OpenGL implementations for rendering of images. It support OpenGL pipeline to accelerate simple and complex images through hardware.
    .
  • Java 2D now supports Bicubic Interpolation.
    .
  • With Java 5 font objects can be created from file or any other stream.

Delivery Process

Delivery and Deployment enhancements are listed here those are introduced with Java 5.

  • Java Web Start and Java Plug-in share common control panel now unlike prior versions where they were having separate control panels to set preferences. Changes made to common control panel apply to both.
    .
  • Security settings now include two levels of security i.e. system level and user level security.
    .
  • Many other deployment properties are added to security settings to allow more control over deployment security features.
    .
  • Enterprise configuration file is introduced which can be accessed through its URL as a web resource. It allows properties having default values of locked values those can be changed at fly.
    .
  • A new compression standard is used to compress jar (Java Archive Files) named as Pack200. Using this compression technique jars can be compression to 1/8th of original size. This helps in downloading Applets through web and also other Java applications.
    .
  • Browser keystores will be used to authenticate security certificates of Java applications and applets. Currently this feature is supported for only Internet Explorer and Mozilla.
    .
  • Now Java Archives can be signed with time stamps. This will help to set expiry dates of the certificate.
    .
  • Java 5 has support for client authentication over HTTPS (here S stands for Secured; HTTPS is a web protocol derived from HTTP and offers secured transfer of data).