he Java 2 Platform, Standard Edition (J2SE) 1.5 (codename: Tiger) has some language-level enhancements that Sun designed to make programmers' lives much easier. This article takes a gander at some of these changes, presenting a number of small Java programs that will showcase some of the key Tiger value adds. (Click here
to download the applications.)
How Do I Get a Peek?
At the time of this article's writing, J2SE 1.5 was still in beta (February 2004 Beta 1 Release). You can download the SDK beta at java.sun.com/j2se. Installation of the beta is a straightforward point-and-click procedure.
One interesting feature of the beta is the ability to choose whether or not to use the new 1.5 features. When compiling your code, you have to explicitly state that you want the Java compiler to use the new 1.5 features. You do this with the following syntax:
javac source 1.5 YourClassName.java
I found the ability to specify this flag especially helpful in understanding how the compiler reacts with and without the new 1.5 feature support.
Parameterized Data Types (a.k.a. Generics)
One of Tiger's key offerings is parameterized data types (also known as generics). generics deliver the ability to have type safe collections. The concept of generics might best be described with an example. In the past, Java programmers could put different object types into a List. Now, they can restrict the types of objects that can be placed in their List collections. If someone tries to place an object that is not of the originally specified datatype, Tiger throws a compile time exception. The following code demonstrates this:
public class GenericExample
public static void main (String args)
// create an ArrayList and restrict contents
// using <ObjectType> following your collection
ArrayList<String> stringList = new ArrayList<String>();
// add a couple of Strings to the ArrayList
// compiler will not allow the following since the
// collection is type-safe (restricted to holding Strings)
// stringList.add(new Integer(8));
// no need to caste when extracting from collection
String fruit = stringList.get(1);
System.out.println("I can't hear you. I have a "
+ fruit + " in my ear!");
When you pull objects from your collection, you no longer have to explicitly caste them. In the code above, for example, you have
String fruit = stringList.get(1); instead of
String fruit = (String)stringList.get(1);.
As you read through this article, you'll notice that Tiger essentially shifts some responsibility for code "writing" to the compiler. For example, in the example above, the compiler handles the explicit casting, which programmers had to perform in previous Java versions.
While playing around with the new Tiger compiler, I also noticed that it teaches the old J2SE dog new tricks. For example, if you try to create an ArrayList without using generics, the compiler warns you that your addition to the collection is "unchecked." (You'll see this firsthand later when you compile some code.)