Featured Post

The great debacle of healthcare.gov

This is the first time in history when the president of the United States of America, or probably for any head of state around the world,...

Sunday, October 28, 2007

Java 5: Tiger @ a glance

New Features of Java 5, the Tiger
The code name Tiger for the Java 1.5 which is officially recognized as Java 5, comes with lot of new features. Those features enrich the capability of Java and also overcome some limitations of faster programming. There are some features those also changed some core beliefs of Java such as Compile time error handling rather Runtime surprising.

Note: This gist is mostly taken from Java 1.5 Tiger: A Developers Notebook from Oreilly

This is the feature that existed long before in the C++ language, known as Template. This feature provides Java the capability to tag a Collection to a specific Object types so that the Collection can only handle the tagged Object type. The main benefits to the programmer are the type safe Collection and avoiding unnecessary type casting.

Type safe Collection

Generic let you to trust the Collection contains a specific type by limiting the type that a particular Collection will accept. You don’t need to cast to the specific object again.

List example:

List myList = new LinkedList();
String str = myList.iterator().next();

Map example:

HashMap myMap = new HashMap();

Limitation: There is a limitation in the Generic Type Safety. This can be broken by using reflection.

Writing Generic types
You can write your own Generic type Collection.

Public class Box
private List list;

public Box()
this.list = new ArrayList();
// Other methods implementation….


Tiger has provided some very useful static method for this type of objects. Those are:
deepToString():This method takes an Array object and prints out it’s contents
deepEquals(): provided to compare multidimensional arrays.


Two cool methods have been provided: offer() and poll() methods are best alternatives add() and remove() methods respectively. The later method throws exception when the Queue is full (for add()) or it is empty (for remove()) but the former method pair returns false and null respectively.

PriorityQueue collection has been given as an alternative to FIFO. This Queue uses a Comparator object to filter; otherwise it works just like a Queue.

The following code is used to print lowest to highest for even and odd numbers.

PriorityQueue pq = new PriorityQueue (20, new Comparator( )
public int compare(Integer i, Integer j)
int result = i%2 - j%2;
if (result == 0)
result = i-j;
return result;

for (int i=0; i<20; i="0;" string=""> antMessages = new EnumMap(AntStatus.class);

antMessages.put(AntStatus.INITIALIZING, “Initializing Ant…..);
String theMsg = antMessage.get(AntStatus.INITIALIZING)

EnumSet has similar uses. See EnumSet JavaDoc API for details

Adding Methods in Enum
You can add methods in an enum just like any other class.

Public enum GuiterFeatures{

private float upCharge;

private GuiterFeatures(float upCharge)
this.upCharge = upCharge;

public String getDescription()
case ROSEWOOD: return “Rosewood back and side”;


Manipulating Enum
Autoboxing and Unboxing
Convertion of Primitives and Wrappers
You can now create any Wrapper class (Integer, Float, Double etc.) without concerning the manual conversion of primitives to wrapper object. Both of the following statements are true:

Integer value = new Integer (10)
Integer newValue = 10;

It is also hassle free to convert the object to primitive type:

int primValue = newValue;

Method overload resolution
Method overloading seems bit confusing in the new Java environment due to the auto boxing and unboxing features. Which overloaded method should be invoked when convert (10) is called if the overloaded method signatures are like follow:

Public int convert(Integer value)
Public int convert(int value);

Tiger has three-pass process to resolve the issue:
i. The compiler attempts to locate the correct method without any boxing, unboxing, or vararg invocations. This will find any method that would have been invoked under Java 1.4 rules.
ii. If the first pass fails, the compiler tries method resolution again, this time allowing boxing and unboxing conventions. Methods with varargs are not considered in this pass.
iii. If the second pass fails, the compiler tries method resolution one last time, allowing boxing and unboxing, and also considers varargs methods.
This relatively simple feature aides you to write simple, cleaner and more flexible code

Creating and iterating

Public void addInstrument(String id, String version, String… features)
this.id = id;
this.version = version;
// here features is the String[] type. You can also convert varargs to List using Arrays.asList(..)
this.features = features

The above method signature accepts variable length of features for the instrument. Those three dots (…) are the syntax of declaring varargs. The following code shows hot it is called:

addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”, “medium startup time”);
addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”);
addInstrument(“1”, “2.2”, “Cool GUI”);

All the above method call will hit the previously declared method with varargas. Great!

Avoiding automatic Array conversion
The loop has gone through a dramatic change in the new release. It is more easy to code now to iterate through collection and string. The new syntax is:

for (declaration : expression)

Example for collection:

For( Object obj : myList)

Advantages of new loop:
i. You can ditch the usage of Iterator as it is done by the Compiler during byte code conversion

Compiler convert the for loop in the following fashion for an collection (in the expression)

for ( Iterator #i = (expression).iterator( ); #i.hasNext( ); )
declaration = #i.next( );

ii. Unnecessary type casting can be avoided by directly using the reference

List wordList = new ArrayList();
for(String word : wordlist)
System.out.print(word + " ");

Apart from above, the new for loop structure (foreach) reduces code in the control structure (you don't need to assign new variable to count and loop through and also another line of code to retrieve the object from the collection 

There are some further points about the syntax of the for/in loop that you should be aware of:
1. Expression must be either an array or an object that implements the java.lang.Iterable interface. The compiler must be able to ensure this at compile-time—so you can't use a List cast to Object, for example, and expect things to behave.

2. The type of the array or Iterable elements must be assignmentcompatible with the type of the variable declared in the declaration . If the assignment won't work, you're going to get errors.

3. The declaration usually consists of just a type and a variable name, but it may include a final modifier and any appropriate annotations (see Chapter 6 on Annotations). Using final prevents the loop variable from taking on any value other than the array or collection element the loop assigns. It also emphasizes the fact that the array or collection cannot be altered through the loop variable.

4. The loop variable of the for/in loop must be declared as part of the loop, with both a type and a variable name. You cannot use a variable declared outside the loop as you can with the for loop.

Static import
Now on you can use the static method name without showing its Class name in every instance through the use of static import.

import static java.lang.System.out;
import static java.util.Math.*;

These following codes are valid now in the class:


double x = sqrt(y * PI)

You can even use the same name in the static import.
Importing multiple members with the same name

Standard annotation types
There are three standard annotation types:
i. Deprecated
ii. Override
iii. SuppressWarning
There are three categories of annotation:
i. Marker annotation
ii. Single-value annotation
iii. Full annotation
You can create your own annotations by using the @interface. The ‘@’ symbol is used to indicate the Interface class to Annotation class.

Yet to cover

Handling uncaught exception
Using Thread safe Collection
Queues blocking
Separating Thread logic from execution logic
Using callable objects
Executing tasks without and ExecutorService
Scheduling Tasks
Advance Synchronization

No comments: