Search This Blog

Monday 15 July 2013

Java 5: New Features

Java 5 new features

http://docs.oracle.com/javase/1.5.0/docs/relnotes/features.html

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

A Generic Java Language Extension

GJ is an extension of the Java programming language that supports generic types.
·         Support for generics. Many data types are generic over some other data type, and this is especially common for reusable libraries such as collection classes. GJ supports the use of such types, for instance allowing one to write the GJ type Vector<String> as opposed to the Java type Vector. With GJ, fewer casts are required, and the compiler catches more errors.
·         Superset of the Java programming language. Every Java source program is still legal and retains the same meaning in GJ. The GJ compiler can be used as a Java compiler.
·         Compiles into the Java Virtual Machine. GJ compiles into JVM code, so GJ programs run on any Java platform, including Java compliant browsers. Class files produced by the GJ compiler can be freely mixed with those produced by other Java compilers.
·         Compatible with existing libraries. One can call any Java library function from GJ, and any GJ library function from Java. Further, where it is sensible, one can assign GJ types to existing Java libraries. For instance, the GJ type Vector<String> is implemented by the Java library type Vector.
·         Efficient translation. GJ is translated by erasure: no information about type parameters is maintained at run-time. This means GJ code is pretty much identical to Java code for the same purpose, and equally efficient.
·         Freely available and fully documented. The GJ compiler is itself written in GJ, so it runs on any platform that supports Java.
·         Related work. There are several related attempts to add generic types to Java, including our previous work on Pizza. GJ differs from these in that it places a premium on compatibility with old Java programs, which is important to developers that want to evolve smoothly from Java to GJ.

GJ is an excellent design and implementation for adding generic types to the Java programming language. It provides a workable and practical facility for the immediate future that can solve many of today's problems in programming and debugging. In the long term, I would hope to see it compatibly extended to carry run-time type parameter information in the manner that Robert Cartwright and I have proposed; but even if that does not occur, GJ as it is currently designed is a useful and workable tool that deserves widespread study and use.
http://homepages.inf.ed.ac.uk/wadler/gj/
Extended for loop
This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays
Extended for loop shortcomings:
The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Autoboxing/Unboxing

This facility eliminates the drudgery of manual conversion between primitive types (such as int) and wrapper types (such as Integer).
http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

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
Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems mentioned above, it allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type.
Suppose you want to add data and behavior to an enum.

public class EnumTest {
      enum Planet {
          MERCURY (3.3e+23,   100,200),
          VENUS   (4.869e+24, 100,200),
          EARTH   (5.976e+24, 100,200),
          MARS    (6.421e+23, 100,200),
          JUPITER (1.9e+27,   100,200),
          SATURN  (5.688e+26, 100,200),
          URANUS  (8.686e+25, 100,200),
          NEPTUNE (1.024e+26, 100,200),
          PLUTO   (1.27e+22,  100,200);

          private final double mass;   // in kilograms
          private final double radius; // in meters
          private final double abc;
          Planet(double mass, double radius, double abc) {
              this.mass = mass;
              this.radius = radius;
              this.abc = abc;
              System.out.println("enum Planet::mass::::"+mass+"::radius::::"+radius+"::abc::::"+abc);
          }
          public double mass()   { return mass; }
          public double radius() { return radius; }

          // universal gravitational constant  (m3 kg-1 s-2)
          public static final double G = 6.67300E-11;

          public double surfaceGravity() {
              return G * mass / (radius * radius);
          }
          public double surfaceWeight(double otherMass) {
              return otherMass * surfaceGravity();
          }
      }
      public static void main(String[] args) {
        double earthWeight = Double.parseDouble("500");
        double mass = earthWeight/Planet.EARTH.surfaceGravity();
        System.out.println(mass);
         for (Planet p : Planet.values()){
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
         }
    }
}

The idea of adding behavior to enum constants can be taken one step further. You can give each enum constant a different behavior for some method. One way to do this by switching on the enumeration constant. Here is an example with an enum whose constants represent the four basic arithmetic operations, and whose eval method performs the operation:
public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}

public class EnumTest1 {
      enum Operation {
          PLUS, MINUS, TIMES, DIVIDE;

          // Do arithmetic op represented by this constant
          double eval(double x, double y){
              switch(this) {
                  case PLUS:   return x + y;
                  case MINUSreturn x - y;
                  case TIMESreturn x * y;
                  case DIVIDE: return x / y;
              }
              throw new AssertionError("Unknown op: " + this);
          }
      }
      public static void main(String[] args) {
       
        
        
         for (Operation p : Operation.values()){
           System.out.printf("Your weight on %s is %f%n",
                             p, p.eval(10, 20));
         }
    }

}
This works fine, but it will not compile without the throw statement, which is not terribly pretty. Worse, you must remember to add a new case to the switch statement each time you add a new constant to Operation. If you forget, the eval method with fail, executing the aforementioned throw statement

http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

Varargs

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

http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

 

Static Import

This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern

http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

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.

 

An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:
@RequestForEnhancement(
    id       = 2868724,
    synopsis = "Enable time-travel",
    engineer = "Mr. Peabody",
    date     = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
An annotation type with no elements is termed a marker annotation type, for example:
/**
* Indicates that the specification of the annotated API element
* is preliminary and subject to change.
*/
public @interface Preliminary { }

 

No comments:

Post a Comment