analytics

Showing posts with label Java versions and their features. Show all posts
Showing posts with label Java versions and their features. Show all posts

Thursday, March 31, 2011

J2SE 5.0 (Tiger) Features

These are the main features of J2SE 5.0 (Tiger)

Generics

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generic provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

How to Use Generics

1. Find a data structure that accepts Object(s)

• ArrayList, LinkedList, HashMap, HashSet
• Not arrays: they already take explicit types!

2. Declare the data structure with the type(s) in angle brackets immediately after class name

• ArrayList myStrings = new ArrayList();
• HashMap myHashtable = new HashMap();

3. Insert objects of the appropriate type

• myStrings.add("Some String");
• myHashtable.put("Some Key", "Some Value");

4. No typecast required on removal

• String myValue = myStrings.get(0);
• String myOtherValue = myHashtable.get("Some Key");


ArrayList Example: Explicit Typecasts

ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();

The cast to Integer on the last line is an example of the typecasting issues that generic types aim to prevent. The issue is that the 1.4.2 Collection API uses the Object class to store the Collection objects, which means that it cannot pick up type mismatches at compile time. The first notification of a problem is a ClassCastException at runtime.

The same example with the generified Collections library is written as follows:

ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = list.get(0).intValue();


Automatic Boxing and Unboxing of Primitive Types

As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

Before

ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();

After

ArrayList list = new ArrayList();
list.add(0, 42);
int total = list.get(0);



The For-Each Loop

The Iterator class is used heavily by the Collections API. It provides the mechanism to navigate sequentially through a Collection. The new enhanced for loop can replace the iterator when simply traversing through a Collection as follows. The compiler generates the looping code necessary and with generic types no additional casting is required.

The for (:) loop is designed for iteration over array and collections.

Iterating over Arrays:

for (;;) Loop
int[] ageInfo = {12, 30, 45, 55};
int sumAge = 0;
for (int i = 0; i < ageInfo.length; i++)
sumAge += ageInfo[i];

for (:) Loop

int[] ageInfo = {12, 30, 45, 55};
int sumAge = 0;
for (int element : ageInfo)
sumAge += element;

Note that an array element of a primitive value cannot be modified in the for(:) loop.

Iterating over non-generic Collections:

for(;;) Loop

Collection nameList = new ArrayList();
nameList.add("Tom");
nameList.add("Dick");
nameList.add("Harry");
for (Iterator it = nameList.iterator();
it.hasNext(); ) {
Object element = it.next();
if (element instanceof String) {
String name = (String) element;
//...
}
}

for(:) Loop

Collection nameList = new ArrayList();
nameList.add("Tom");
nameList.add("Dick");
nameList.add("Harry");
for (Object element : nameList) {
if (element instanceof String) {
String name = (String) element;
//...
}
}


Static Import

An import statement allows you to give a hint to the compiler as to which class you are
referring to in your code. It gives you the convenience of using the short name for a class
(like JButton) instead of the long, fully qualified name (like javax.swing.JButton).
Remember that import does not tell the compiler where the class resides (classpath does
that). It only tells the compiler which class you mean to use.

Syntax:

// Static-import-on-demand: imports all static members
import static FullyQualifiedTypeName.*;
// Single-static-import: imports a specific static member
import static FullyQualifiedTypeName.StaticMemberName;

Avoiding the Constant Interface Antipattern

Constant Interface

package mypackage;

public interface MachineStates {
// Fields are public,
// static and final.
int BUSY = 1;
int IDLE = 0;
int BLOCKED = -1;
}


Without Static Import

class MyFactory implements
mypackage.MachineStates {
public static void main(String[] args) {
int[] states = {IDLE, BUSY, IDLE, BLOCKED };
for (int s : states)
System.out.println(s);
}
}

With Static Import

import static mypackage.MachineStates.*; // Imports all static members.

class MyFactory2 {
public static void main(String[] args) {
int[] states = { IDLE, BUSY, IDLE, BLOCKED };
for (int s : states)
System.out.println(s);
}
}

Static-import-on-demand: Import of All Static Members

Without Static Import

class Calculate1 {
public static void main(String[] args) {
double x = 10.0, y = 20.5;
double squareroot = Math.sqrt(x);
double hypotenue = Math.hypot(x, y);
double area = Math.PI * y * y;
}
}


With Static Import

import static java.lang.Math.*;

// All static members from Math are imported.
class Calculate2 {
public static void main(String[] args) {
double x = 10.0, y = 20.5;
double squareroot = sqrt(x);
double hypotenue = hypot(x, y);
double area = PI * y * y;
}
}

Single-static-import: Import of Individual Static Members

import static java.lang.Math.sqrt; // Static method
import static java.lang.Math.PI; // Static field
// Only specified static members are imported.
class Calculate3 {
public static void main(String[] args) {
double x = 10.0, y = 20.5;
double squareroot = sqrt(x);
double hypotenue = Math.hypot(x, y); // Requires type name.
double area = PI * y * y;
}
}


Enums

Enumerated Types

• An enumerated type defines a finite set of symbolic names and their values.
• Standard approach is the int enum pattern (or the analogous String enum pattern):

public class MachineState {
public static final int BUSY = 1;
public static final int IDLE = 0;
public static final int BLOCKED = -1;
//...
}

public class Machine {
int state;
public void setState(int state) {
this.state = state;
}
//...
}

public class IntEnumPatternClient {
public static void main(String[] args) {
Machine machine = new Machine();
machine.setState(MachineState.BUSY); // (1) Constant qualified by class name
machine.setState(1); // Same as (1)
machine.setState(5); // Any int will do.
System.out.println(MachineState.BUSY); // Prints "1", not "BUSY".
}
}

Some Disadvantages of the int Enum Pattern

• Not typesafe.
– Any int value can be passed to the setState() method.

• No namespace.
– A constant must be qualified by the class (or interface) name, unless the class is extended (or the interface is implemented).

• Uninformative textual representation.
– Only the value can be printed, not the name.

• Constants compiled into clients.
– Clients need recompiling if the constant values change.

Typesafe Enum Construct

• The enum construct provides support for enum types:

enum MachineState { BUSY, IDLE, BLOCKED } // Canonical form
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

• Keyword enum is used to declare an enum type.

• Overcomes all the disadvantages of the int enum pattern, and is more powerful

Properties of the Enum Type


• An enum declaration is a special kind of class declaration:
– It can be declared at the top-level and as static enum declaration.

// (1) Top level enum declaration
public enum SimpleMeal
{ BREAKFAST, LUNCH, DINNER }


public class EnumTypeDeclarations {
// (2) Static enum declaration is OK.
public enum SimpleMeal
{ BREAKFAST, LUNCH, DINNER };
public void foo() {
// (3) Local (inner) enum declaration is NOT OK!
enum SimpleMeal
{ BREAKFAST, LUNCH, DINNER }
}
}

Enum Constructors

• Each constant declaration can be followed by an argument list that is passed to the
constructor of the enum type having the matching parameter signature.

– An implicit standard constructor is created if no constructors are provided for the enum type.

– As an enum cannot be instantiated using the new operator, the constructors cannot be called explicitly.

public enum Meal {
BREAKFAST(7,30), LUNCH(12,15), DINNER(19,45);
Meal(int hh, int mm) {
assert (hh >= 0 && hh <= 23): "Illegal hour.";
assert (mm >= 0 && hh <= 59): "Illegal mins.";
this.hh = hh;
this.mm = mm;
}

// Time for the meal.
private int hh;
private int mm;
public int getHour() { return this.hh; }
public int getMins() { return this.mm; }
}

Methods Provided for the Enum Types

• Names of members declared in an enum type cannot conflict with automatically generated member names:

– The enum constant names cannot be redeclared.

– The following methods cannot be redeclared:

static []values()

Returns an array containing the constants of this enum class, in the order they are declared.

static valueOf(String name)

Return the enum constant with the specified name


• Enum types are based on the java.lang.Enum class which provides the default behavior.

• Enums cannot declare methods which override the final methods of the java.lang.Enum class:

– clone(), compareTo(Object), equals(Object), getDeclaringClass(), hashCode(), name(), ordinal().

– The final methods do what their names imply, but the clone() method throws an CloneNotSupportedException, as an enum constant cannot be cloned.

• Note that the enum constants must be declared before any other declarations in an enum type.

public class MealClient {
public static void main(String[] args) {
for (Meal meal : Meal.values())
System.out.println(meal + " served at " + meal.getHour() + ":" + meal.getMins() + ", has the ordinal value " +  meal.ordinal());
}
}


Output from the program:

BREAKFAST served at 7:30, has the ordinal value 0
LUNCH served at 12:15, has the ordinal value 1
DINNER served at 19:45, has the ordinal value 2


Enums in a switch statement


• The switch expression can be of an enum type, and the case labels can be enum constants of this enum type.

public class EnumClient {
public static void main(String[] args) {
Machine machine = new Machine();
machine.setState(MachineState.IDLE);
// ...
MachineState state = machine.getState();
switch(state) {
//case MachineState.BUSY:// Compile error: Must be unqualified.
case BUSY: System.out.println(state + ": Try later."); break;
case IDLE: System.out.println(state + ": At your service."); break;
case BLOCKED: System.out.println(state + ": Waiting on input."); break;
//case 2: // Compile error: Not unqualified enum constant.
default: assert false: "Unknown machine state: " + state;
}
}
}


Varargs


Assume you want to invoke a method with variable number of arguments. The option we
had on hand in Java 1.4 or earlier was to pass an array. Let’s consider a simple example
as shown below:

public static int max(int[] values)
{
int max = values[0];
for(int aValue : values)
{
if (aValue > max) max = aValue;
}
return max;
}

We can invoke this method by passing an array with different number of values as illustrated below:

max(new int[] {1, 7, 2, 9, 8});
max(new int[]{8, 12, 87, 23, 1, 3, 6, 9, 37});

In order to invoke a method that takes variable number of arguments, we had to bundle
the parameters into an array. While this works, it is not elegant. The varargs introduced in
Java 5 addresses the elegance issue.

It is not only elegant, it also is very type safe. Let’s take the max method and modify it to use the varargs.

public static int max(int... values)

Notice that the only thing I changed is int[] to int… and I did not modify the
implementation of the max method. If the previous implementation of the method still
works after the change to the parameter type, then what is the new syntax and how is it
related to the array?

A type followed by … is simply a syntax sugar–it’s nothing but an array. However, the
compiler allows you to pass either an array or a discrete set of values to this method. For
example, now I can call the modified max method as follows:

max(new int[] {1, 7, 2, 9, 8});
max(new int[]{8, 12, 87, 23, 1, 3, 6, 9, 37});

max(1, 7, 2, 9, 8);
max(8, 12, 87, 23, 1, 3, 6, 9, 37);

There’s less clutter in the bottom two lines than in the top two lines. But what’s going on
when you pass discrete values? The compiler simply rolls the values into an array. So, the

code:

max(1, 7);
is compiled into:
max(new int[] {1, 7});

In the above example we passed an array of int. What if we want to pass different types
of data? Sure we can. Consider the example below:

public static void print(Object... values)
{
for(Object obj : values)
{
System.out.printf("%s is of type %s\n", obj, obj.getClass().getName());
}
}

The above code receives a varargs of type Object. You can invoke it with different types as shown below:

print(1, "test", 'a', 2.1);

The output from this call is:

1 is of type java.lang.Integer test is of type java.lang.String a is of type java.lang.Character
2.1 is of type java.lang.Double


The first line should be no surprise if you kept autoboxing in mind–that is the reason for
the type to be Integer instead of int. We’ve also used the printf statement which
directly benefits from the varargs concept.

You are not restricted to having only varargs as parameters, that is, you can have regular
parameters and varargs, if you like. However, varargs, if present, must be trailing. In
other words, place any regular parameters you like and then place the varargs as shown in

the following example:

public static void print(String msg, Object... values)

Pros and Cons:

• varargs comes in handy when you want to pass variable number of arguments.
Use it if you need that flexibility and elegance.

• You loose some compile time type safety if your varargs is of type Object.
However, if it is specific type (like int…), then you have type safety.

• If in your application you expect only three or four parameters to be passed to the
method, then don’t bother to use varargs.

• If you are not careful, you may have trouble with method overloading as the
varargs may increase the chance of parameter collision when methods are overloaded.


Annotations

Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. Here is an example of class annotation:

@MyAnnotation(name="someName", value = "Hello World")
public class TheClass {
}

The class TheClass has the annotation @MyAnnotation written ontop. Annotations are defined like interfaces. Here is the MyAnnotation definition:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)

public @interface MyAnnotation {
public String name();
public String value();
}

The @ in front of the interface marks it as an annotation. Once you have defined the annotation you can use it in your code, as shown in the earlier examples.

The two directives in the annotation definition, @Retention(RetentionPolicy.RUNTIME) and@Target(ElementType.TYPE), specifies how the annotation is to be used.

@Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. If you do not set this directive, the annotation will not be preserved at runtime, and thus not available via reflection.

@Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces typically). You can also specify METHOD or FIELD, or you can leave the target out alltogether so the annotation can be used for both classes, methods and fields.

Class Annotations

You can access the annotations of a class, method or field at runtime. Here is an example that accesses the class annotations:

Class aClass = TheClass.class;
Annotation[] annotations = aClass.getAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}

You can also access a specific class annotation like this:

Class aClass = TheClass.class;
Annotation annotation = aClass.getAnnotation(MyAnnotation.class);
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}

Method Annotations

Here is an example of a method with annotations:

public class TheClass {
@MyAnnotation(name="someName", value = "Hello World")
public void doSomething(){}
}

You can access method annotations like this:

Method method = ... //obtain method object
Annotation[] annotations = method.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}

You can also access a specific method annotation like this:

Method method = ... // obtain method object
Annotation annotation = method.getAnnotation(MyAnnotation.class);
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}


Parameter Annotations

It is possible to add annotations to method parameter declarations too. Here is how that looks:

public class TheClass {
public static void doSomethingElse(
@MyAnnotation(name="aName", value="aValue") String parameter){
}
}

You can access parameter annotations from the Method object like this:

Method method = ... //obtain method object
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();
int i=0;
for(Annotation[] annotations : parameterAnnotations){
Class parameterType = parameterTypes[i++];
for(Annotation annotation : annotations){
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("param: " + parameterType.getName());
System.out.println("name : " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
}

Notice how the Method.getParameterAnnotations() method returns a two-dimensionalAnnotation array, containing an array of annotations for each method parameter.

Field Annotations

Here is an example of a field with annotations:

public class TheClass {
@MyAnnotation(name="someName", value = "Hello World")
public String myField = null;
}

You can access field annotations like this:

Field field = ... //obtain field object
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}

You can also access a specific field annotation like this:

Field field = ... // obtain method object
Annotation annotation = field.getAnnotation(MyAnnotation.class);
if(annotation instanceof MyAnnotation){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}


Other features

In this article we have focused on the language features in Java 5. Java 5 has some other

interesting features as well. Listed below are some select features:

• StringBuilder
– StringBuffer eliminates object creation overhead, but has synchronization overhead
– StringBuilder removes that overhead

• Client vs. Server side differences in garbage collection, more adaptive collection

• Improved Image I/O for performance and memory usage

• Reduced application startup time and footprint using shared archive

• Enhancement to Thread Priority

• Ability to get stack trace for a thread or all threads

• UncoughtExceptionHandler on a Thread

• Improved error reporting on fatal exceptions

• System.nanoTime() for nanoseconds granularity for time measurements

• ProcessBuilder

– Easier than Runtime.exec() to start process

• Formatter and Formattable provide ability to format output in printf like style

• Scanner for easier conversion to primitive types – based on regex

• java.lang.instrument allows byte code enhancement at runtime to instrument code

• Collections Framework has Queue, BlockingQueue, and ConcurrentMap interfaces and implementations. Some classes modified to implements new interfaces

• Reflection API supports annotation, enum. Class has been generified

• System.getenv() undeprecated

Tuesday, March 29, 2011

Scripting Language Support in Java SE 6 (Mustang)

You can now mix in JavaScript technology source code, useful for prototyping. Also useful when you have teams with a variety of skill sets. More advanced developers can plug in their own scripting engines and mix their favourite scripting language in with Java code as they see fit.


J2SE 1.6 includes a modified version of the Rhino JavaScript engine integrated via JSR 223 and a command-line scripting shell, jrunscript, which leverages this support. The shell is of limited use in most applications, but can be a valuable tool in learning and prototyping in Java and arbitrary scripting languages. The jrunscript syntax is:

Usage: jrunscript [options] [arguments...]


Accessing the Scripting Engine

The fundamental interface for all scripting engines is javax.script.ScriptEngine. This interface defines a set of methods expected to be supported by all implementations. An implementation is obtained from the ScriptEngineManager. ScriptEngine implementations are deployed as Jar files (typically in lib/ext). Each such jar contains a text file resource META-INF/services/javax.script.ScriptEngineFactory defining one or more classes implementing ScriptEngineFactory. The ScriptEngineManager utilizes these factories to create specific implementations. The ScriptEngineManager also provides metadata defining the supported script type and version information which is used to resolve requests for a scripting implementation. Obtaining an engine is straightforward:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine jsEngine = manager.getEngineByName("js");

The primary method of the ScriptEngine, eval(), executes a script directly passed as a String or accessed through a Reader. These two variations may be additionally parameterized with either a Bindings or ScriptContext object.

Object eval(String script)
Object eval(Reader reader)
Object eval(String script, Bindings n)
Object eval(Reader reader, Bindings n)
Object eval(String script, ScriptContext context)
Object eval(Reader reader, ScriptContext context)


A ScriptContext associates a ScriptEngine with objects in the Java application. Every engine has a default ScriptContext (which can be altered through the API). It groups objects by scope. Each scope has a related Bindings instance containing these objects. Bindings is simply a Map which associates scripting variable names with Java instances.

Two scopes are predefined, ScriptContext.GLOBAL_SCOPE and ScriptContext.ENGINE_SCOPE. The first contains attributes shared by all Engines created via a given factory, while the second is specific to the engine implementation. The default context and scope is used by the single argument eval() methods. The Scripting API includes many instances of such convenience methods. A binding or context passed to an eval effectively replaces the default bindings or context for the scope of the method call.

Additional scopes may be defined by contexts specific to an Engine. For example, the HttpScriptContext used in web-based applications defines request, session, and applications scopes corresponding to Servlet scopes.

The below example summarizes basic usage of the Scripting API:

// simple script execution
jsEngine.eval("print('Hello')");

// bind scripting variables and use in a script
jsEngine.put("a", 3);
Integer b = 2;
jsEngine.put("b", b);
Object retval = jsEngine.eval("c = a + b; print('a + b = ' + c);");

// retrieve the bindings we previously added
Bindings bindings = jsEngine.getBindings(ScriptContext.ENGINE_SCOPE);
boolean containsKey = bindings.containsKey("a");
System.out.println(containsKey);

Results in:

Hello
a + b = 5
true



The checked ScriptException is thrown by methods of the Scripting API. Depending on the Engine, the errant line and column number of the script will be included in the exception.

Compilable and Invocable

Beyond the based ScriptEngine capability, certain implementations may advertise additional capability by implementing the Compilable or Invocable interfaces.

An engine implementing Compilable supports the re-execution of intermediate (e.g. compiled) code from previous compilations. The compile() method returns a CompiledScript based on either a String or Reader. The CompiledScript may be executed repeatedly via its eval() method.

Compilable eng = (Compilable)jsEngine;
CompiledScript script = eng.compile("function test() { return 10; }; test();");
Object compiledOutput = script.eval();
System.out.println(compiledOutput); // prints 10.0

An engine implementing Invocable supports the calling of individual functions scripted in the engine via the invoke() method. Arguments and return values are converted between script and Java types based on the engine implementation. Below is a simple example:

jsEngine.eval("function test(val) { return val; }");
Invocable jsInvoke = (Invocable)jsEngine;
Object invoke = jsInvoke.invoke("test", new Object[] {111.0});
System.out.println(invoke); // prints 111.0

Scripts may be used to implement arbitrary interfaces without direct dependence on the given interface. The following example illustrates definition of a run() method which is bound as the implementation of a Runnable interface at runtime based only on method signature. Below, the invoke() and run() calls invoke the same underlying scripted method.

jsEngine.eval("function run() { print ('running..'); }");
Object invoke2 = jsInvoke.invoke("run",null); // prints running...

Runnable r = jsInvoke.getInterface(Runnable.class);
r.run(); // prints running...

Enhancements in Java SE 6 (Mustang)

Web Services (Improved Web Service support)


All developers get first-class support for writing XML web service client applications. No messing with the plumbing: You can expose your APIs as .NET interoperable web services with a simple annotation. Not your style? Want to handle the XML directly? Knock yourself out: Java SE 6 adds new parsing and XML to Java object-mapping APIs, previously only available in Java EE platform implementations or the Java Web Services Pack.



Scripting (Scripting Language Support)


You can now mix in JavaScript technology source code, useful for prototyping. Also useful when you have teams with a variety of skill sets. More advanced developers can plug in their own scripting engines and mix their favourite scripting language in with Java code as they see fit.


 
Database (JDBC 4.0 support)


For a great out-of-the-box development experience with database applications, the Java SE 6 development kit – though not the Java Runtime Environment (JRE) – co-bundles the all-Java JDBC database, Java DB based on Apache Derby. No more need to find and configure your own JDBC database when developing a database application! Developers will also get the updated JDBC 4.0, a well-used API with many important improvements, such as special support for XML as an SQL datatype and better integration of Binary Large OBjects (BLOBs) and Character Large OBjects (CLOBs) into the APIs.



More Desktop APIs

GUI developers get a large number of new tricks to play like the ever popular yet newly incorporated SwingWorker utility to help you with threading in GUI apps, JTable sorting and filtering, and a new facility for quick splash screens to quiet impatient users.



Monitoring and Management

The really big deal here is that you don't need do anything special to the startup to be able to attach on demand with any of the monitoring and management tools in the Java SE platform. Java SE 6 adds yet more diagnostic information, and we co-bundled the infamous memory-heap analysis tool Jhat for forensic explorations of those core dumps.



Compiler Access

Really aimed at people who create tools for Java development and for frameworks like JavaServer Pages (JSP) or Personal Home Page construction kit (PHP) engines that need to generate a bunch of classes on demand, the compiler API opens up programmatic access to javac for in-process compilation of dynamically generated Java code. The compiler API is not directly intended for the everyday developer, but for those of you deafened by your screaming inner geek, roll up your sleeves and give it a try. And the rest of us will happily benefit from the tools and the improved Java frameworks that use this.



Pluggable Annotations

It is becoming a running joke in Java technology circles, at least some that contain us, that for every wished-for feature missing in Java technology, there's a budding annotation that will solve the problem. Joke no more, because Java tool and framework vendors can put a different smile on your face, defining their own annotations and have core support for plugging in and executing the processors that do the heavy lifting that can make custom annotations so cool.



Desktop Deployment

Those of you deploying applications to the desktop will soon discover that it's a tale of a large number of smaller changes that add up to a big difference to existing applications: better platform look-and-feel in Swing technology, LCD text rendering, and snappier GUI performance overall. Java applications can integrate better with the native platform with things like new access to the platform's System Tray and Start menu. At long last, Java SE 6 unifies the Java Plug-in technology and Java WebStart engines, which just makes sense. Installation of the Java WebStart application got a much needed makeover.



Security

You can have all the security features you like in the platform — and this release adds a few more, like the XML-Digital Signature (XML-DSIG) APIs for creating and manipulating digital signatures — but if you don't have well supported security administrators, your security may be at risk. So Java SE 6 has simplified the job of its security administrators by providing various new ways to access platform-native security services, such as native Public Key Infrastructure (PKI) and cryptographic services on Microsoft Windows for secure authentication and communication, Java Generic Security Services (Java GSS) and Kerberos services for authentication, and access to LDAP servers for authenticating users.



Quality, Compatibility, Stability

You probably knew that Sun has done regular feature releases of the Java SE platform over the last 10 years. So we certainly feel like we've built up some expertise in this area, such as the ever growing 80,000 test cases and several million lines of code testing conformance (being just one aspect of our testing activity). You probably noticed that, unlike the last release, people have been downloading binary snapshots for the last 20 (not just 6) months. And what's more, they've been filing bugs. So, before we even got to beta, we'd fixed a number of quality and regression issues. Doesn't that add up to a better product? Oh, and by the way, performance is looking better than J2SE 5.0.

Java versions and their features

Java versions and their features


The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process (JCP), which uses Java Specification Requests (JSRs) to propose and specify additions and changes to the Java platform. The language is specified by the Java Language Specification (JLS); changes to the JLS are managed under JSR 901.

In addition to the language changes, much more dramatic changes have been made to the Java class library over the years, which has grown from a few hundred classes in JDK 1.0 to over three thousand in J2SE 5000 Entire new APIs, such as Swing and Java2D, have been introduced, and many of the original JDK 1.0 classes and methods have been deprecated.

JDK 1.0 (January 23, 1996)

-----------------------------
Codename Oak. Initial release the first stable version was the JDK 1.0.2. is called Java 1

 
JDK 1.1 (February 19, 1997)

-------------------------------
Major additions included:

  • an extensive retooling of the AWT event model

  • inner classes added to the language

  • JavaBeans

  • JDBC

  • RMI

  • Reflection which supported Introspection only, no modification at runtime was possible.

 
J2SE 1.2 (December 8, 1998)

-------------------------------
Codename Playground. This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 and the version name "J2SE" (Java 2 Platform, Standard Edition) replaced JDK to distinguish the base platform from J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition). Major additions included:

  • strictfp keyword

  • the Swing graphical API was integrated into the core classes

  • Sun's JVM was equipped with a JIT compiler for the first time

  • Java Plug-in

  • Java IDL, an IDL implementation for CORBA interoperability

  • Collections framework

  
J2SE 1.3 (May 8, 2000)

---------------------------
Codename Kestrel. The most notable changes were:

  • HotSpot JVM included (the HotSpot JVM was first released in April, 1999 for the J2SE 1.2 JVM)

  • RMI was modified to support optional compatibility with CORBA

  • JavaSound

  • Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension)

  • Java Platform Debugger Architecture (JPDA)

  • Synthetic proxy classes


J2SE 1.4 (February 6, 2002)

-------------------------------
Codename Merlin. This was the first release of the Java platform developed under the Java Community Process as JSR 59. Major changes included:

  • assert keyword (Specified in JSR 41.)

  • regular expressions modeled after Perl regular expressions

  • exception chaining allows an exception to encapsulate original lower-level exception

  • Internet Protocol version 6 (IPv6) support

  • Non-blocking NIO (New Input/Output) (Specified in JSR 51.)

  • logging API (Specified in JSR 47.)

  • image I/O API for reading and writing images in formats like JPEG and PNG

  • integrated XML parser and XSLT processor (JAXP) (Specified in JSR 5 and JSR 63.)

  • integrated security and cryptography extensions (JCE, JSSE, JAAS)

  • Java Web Start included (Java Web Start was first released in March, 2001 for J2SE 1.3) (Specified in JSR 56.)

  • Preferences API (java.util.prefs)

 
J2SE 5.0 (September 30, 2004)

----------------------------------
Codename Tiger. Originally numbered 1.5, which is still used as the internal version number. This version was developed under JSR 176.

J2SE 5.0 entered its end-of-life on April 8, 2008 and is no longer supported by Sun as of November 3, 2009.

Tiger added a number of significant new language features:

  • Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). (Specified by JSR 14.)

  • Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)

  • Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.)

  • Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)

  • Swing: New skinnable look and feel, called synth.

  • Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.

  • Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable

  • Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory.

  • Automatic stub generation for RMI objects.

  • Static imports

  • Java 5 is the last release of Java to officially support the Microsoft Windows 9x line (Windows 95, Windows 98, Windows ME). Unofficially, Java SE 6 Update 7 (1.6.0.7) is the last version of Java to be shown working on this family of operating systems.

  • The concurrency utilities in package java.util.concurrent.

  • Scanner class for parsing data from various input streams and buffers.

Java SE 6 (December 11, 2006)

-----------------------------------
Codename Mustang. As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the version number. Internal numbering for developers remains 1.6.0.This version was developed under JSR 270.

During the development phase, new builds including enhancements and bug fixes were released approximately weekly. Beta versions were released in February and June 2006, leading up to a final release that occurred on December 11, 2006. The current revision is Update 24 which was released in February 2011.

Major changes included in this version:

  • Support for older Win9x versions dropped. Unofficially Java 6 Update 7 is the last release of Java shown to work on these versions of Windows. This is believed to be due to the major changes in Update 10.

  • Scripting Language Support (JSR 223): Generic API for tight integration with scripting languages, and built-in Mozilla JavaScript Rhino integration

  • Dramatic performance improvements for the core platform, and Swing.

  • Improved Web Service support through JAX-WS (JSR 224)

  • JDBC 4.0 support (JSR 221).

  • Java Compiler API (JSR 199): an API allowing a Java program to select and invoke a Java Compiler programmatically.

  • Upgrade of JAXB to version 2.0: Including integration of a StAX parser.

  • Support for pluggable annotations (JSR 269)

  • Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).

  • JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.
Java SE 6 has already released it's 24th update on February 15, 2011


Java SE 7

-----------
Java 7 (codename Dolphin) is an upcoming major update to Java. The development period is organized into thirteen milestones; on February 18, 2011, milestone 13, the last milestone was reached. Multiple builds, which generally include enhancements and bug fixes, are released per milestone. The Feature list at the Open JDK 7 project lists many of the expected feature changes.

The expected feature additions for Java 7

  • JVM support for dynamic languages, following the prototyping work currently done on the Multi Language Virtual Machine

  • Compressed 64-bit pointers

  • Language changes under Project Coin. The features accepted for inclusion in Project Coin are:

  • Strings in switch

  • Automatic resource management

  • Improved Type Inference for Generic Instance Creation

  • Simplified Varargs Method Invocation

  • Better integral literals allowing for underscores as digit separators

  • Language-level support for Collections

  • Concurrency utilities under JSR 166

  • New file I/O library to enhance platform independence and add support for metadata and symbolic links. The new packages are java.nio.file and java.nio.file.attribute

  • Library-level support for Elliptic curve cryptography algorithms

  • An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs

  • New platform APIs for the graphics features originally planned for release in Java version 6u10

  • Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol

  • Upstream updates to XML and Unicode


Java SE 8

------------
Java 8 is expected in late 2012 and will include at a minimum the features that were planned for Java 7 but later deferred.

  • Modularization of the JDK under Project Jigsaw

  • Language-level support for lambda expressions (officially, lambda expressions; unofficially, closures) under Project Lambda. There was an ongoing debate in the Java community on whether to add support for lambda expressions. Sun later declared that lambda expressions would be included in Java 7 and asked for community input to refine the feature.

  • Parts of project Coin that are not included in Java 7


I will post soon on J2SE 1.4 (Merlin), J2SE 5.0 (tiger) and Java SE 6 (mustang) features