JDK Evolutions

  • Upload
    konaven

  • View
    263

  • Download
    0

Embed Size (px)

Citation preview

  • 8/3/2019 JDK Evolutions

    1/14

    JDK Evolutions

  • 8/3/2019 JDK Evolutions

    2/14

    Versions

    VERSION CODE NAME RELEASE DATE

    JDK 1.1.4 Sparkler Sept 12, 1997JDK 1.1.5 Pumpkin Dec 3, 1997JDK 1.1.6 Abigail April 24, 1998JDK 1.1.7 Brutus Sept 28, 1998JDK 1.1.8 Chelsea April 8, 1999

    J2SE 1.2 Playground Dec 4, 1998J2SE 1.2.1 (none) March 30, 1999J2SE 1.2.2 Cricket July 8, 1999J2SE 1.3 Kestrel May 8, 2000J2SE 1.3.1 Ladybird May 17, 2001J2SE 1.4.0 Merlin Feb 13, 2002J2SE 1.4.1 Hopper Sept 16, 2002J2SE 1.4.2 Mantis June 26, 2003J2SE 5.0 (1.5.0) Tiger Sept 29, 2004J2SE 5.1 Dragon Merged into mustang

    Future ReleasesJ2SE 6.0 (1.6.0) Mustang Not yet releasedJ2SE 7.0 (1.7.0) Dolphin Not yet released

  • 8/3/2019 JDK Evolutions

    3/14

    JDK Differences

    Java is compatible between versions. Old code will run,even without recompilation, on new JVMs, and new codewill run on old JVMs as long as you avoid new features,and you use the -target compiler option.

    1.1 added a totally new event model, using Listeners.This is the level Microsoft has trapped many of itscustomers at.

    1.2 added ArrayList and other Collections. 1.3 added Swing.

    1.4 added assertions and nio.

    1.5 added generics, enumerations and annotations

  • 8/3/2019 JDK Evolutions

    4/14

    JDK 5.0 Language Features

    Generics Adds compile-time type safety to the Collections

    Framework & eliminates casting during retrieval

    Enhanced For Loop Eliminates the error-proneness of iterators and indexvariables when iterating over collections and arrays.

    Autoboxing / Unboxing This facility eliminates the manual conversion between

    primitive types and wrappers

    Typesafe Enums This flexible object-oriented enumerated type facilityallows you to create enumerated types with arbitrarymethods and fields. It provides all the benefits of theTypesafe Enum Varargs. This facility eliminates the needfor manually boxing up argument lists into an array wheninvoking methods that accept variable-length arguments

    Static import This facility lets you avoid qualifying static members withclass names without the shortcomings of the "ConstantInterface antipattern.

    Annotations NA ( Meta Data )

  • 8/3/2019 JDK Evolutions

    5/14

    Generics

    // Removes 4-letter words from Collection. Elements must be strings ( Traditional ) Public static void expurgate(Collection c)

    {for (Iterator i = c.iterator(); i.hasNext(); ){

    if (((String) i.next()).length() == 4){

    i.remove();

    }}}

    // Removes 4-letter words from Collection. Elements must be strings ( Generics ) Public static void expurgate(Collection c) {

    for (Iterator i = c.iterator(); i.hasNext(); ){

    if (i.next().length() == 4){

    i.remove();}

    }}You should use generics everywhere you can. The extra effort in generifying code is well worth the gains in clarity and type safetySet s = new HashSet();

  • 8/3/2019 JDK Evolutions

    6/14

    Enhanced For Loop

    void cancelAll(Collection c)

    {

    for (Iterator i = c.iterator(); i.hasNext(); )

    {

    i.next().cancel();

    }}

    void cancelAll(Collection c)

    {

    for (TimerTask t : c)

    {

    t.cancel();

    }

    }

  • 8/3/2019 JDK Evolutions

    7/14

    Enhanced For Loop ( Contd..)

    for (Iterator i = suits.iterator(); i.hasNext(); )

    {

    for (Iterator j = ranks.iterator(); j.hasNext(); )

    {

    sortedDeck.add(new Card(i.next(), j.next()));

    }

    }

    ?? What is the problem in the code ???

    // BROKEN - throws Exception!

    // Fixed, though a bit ugly

    for (Iterator i = suits.iterator(); i.hasNext(); )

    {

    Suit suit = (Suit) i.next();

    for (Iterator j = ranks.iterator(); j.hasNext(); )

    {

    sortedDeck.add(new Card(suit, j.next()));

    }

    }

  • 8/3/2019 JDK Evolutions

    8/14

    Enhanced For Loop ( Contd..)

    for (Suit suit : suits){

    for (Rank rank : ranks){

    sortedDeck.add(new Card(suit, rank));}

    }

    ** The for-each loop hides the iterator. Therefore, the for-each loop is not usable for filtering. Similarly itis 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. **

    // Returns the sum of the elements of arrayint sum(int[] a){

    int result = 0;for (int i : a)

    result += i;return result;

    }

    ** The for-each construct is also applicable to arrays, where it hides the index variable rather than theiterator **

  • 8/3/2019 JDK Evolutions

    9/14

    Autoboxing / unboxing

    Boxing means wrapping primitives using their Wrapper Objects

    // Prints a frequency table of the words on the command line public class Frequency {

    public static void main(String[] args) {

    Map m = new TreeMap();for (String word : args)

    {Integer freq = m.get(word);m.put(word, (freq == null ? 1 : freq + 1));

    }System.out.println(m);

    }}

    java Frequency if it is to be it is up to me to do the watusi {be=1, do=1, if=1,is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}

  • 8/3/2019 JDK Evolutions

    10/14

    Autoboxing / Unboxing (Contd..)

    // List adapter for primitive int array public static List asList(final int[] a) {

    return new AbstractList(){

    public Integer get(int i){

    return a[i];

    } // Throws NullPointerException if val == null

    public Integer set(int i, Integer val){

    Integer oldVal = a[i];a[i] = val;return oldVal;

    }public int size()

    {return a.length;

    }};

    }The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It isplenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop.

  • 8/3/2019 JDK Evolutions

    11/14

    Enums

    // int Enum Pattern - has severe problems! ( Traditional )

    public static final int SEASON_WINTER = 0;

    public static final int SEASON_SPRING = 1;

    public static final int SEASON_SUMMER = 2;

    public static final int SEASON_FALL = 3;

    Not typesafe - Since a season is just an int you can pass in any other int value where a season is required.

    No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoidcollisions with other int enum types.

    Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a newconstant is added between two existing constants or the order is changed, clients must be recompiled. If they arenot, they will still run, but their behavior will be undefined.

    Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, whichtells you nothing about what it represents, or even what type it is.

    // new way

    enum Season { WINTER, SPRING, SUMMER, FALL }

    private final Season _season ;

    Season.values())

    The new enum declaration defines a full-fledged class

    add arbitrary methods and fields to an enum type

    implement arbitrary interfaces

  • 8/3/2019 JDK Evolutions

    12/14

    Varargs

    public static String format(String pattern, Object... arguments);

    The three periods after the final parameter's type indicate that the final argument may be passedas an array oras a sequence of arguments. Varargs can be used onlyin the final argumentposition.

    System.out.printf("%s failed: %s%n", className, ex);

  • 8/3/2019 JDK Evolutions

    13/14

    Static Import

    // Traditional Way

    double r = Math.cos(Math.PI * theta);

    // New way

    import static java.lang.Math.*;

    double r = cos(PI * theta);

  • 8/3/2019 JDK Evolutions

    14/14

    java.lang.ProcessBuilder : provides a more convenient way to invoke subprocesses than doesRuntime.exec. In particular, ProcessBuilder makes it easy to start a subprocess with a modifiedprocess environment

    java.util.Formatter : An interpreter for printf-style format strings, the Formatter class providessupport for layout justification and alignment, common formats for numeric, string, and date/timedata, and locale-specific output

    java.util.Scanner class can be used to convert text into primitives or Strings. Since it is based on

    thejava.util.regex package, it also offers a way to conduct regular expression based searches onstreams, file data, strings

    Task Scheduling Framework - The Executor framework is a framework for standardizinginvocation, scheduling, execution, and control of asynchronous tasks according to a set ofexecution policies. Implementations are provided that allow tasks to be executed within thesubmitting thread, in a single background thread (as with events in Swing), in a newly createdthread, or in a thread pool, and developers can create of Executor supporting arbitrary executionpolicies. The built-in implementations offer configurable policies such as queue length limits and

    saturation policy which can improve the stability of applications by preventing runaway resourceconsumption

    public void addShutdownHook(Thread hook)

    Registers a new virtual-machine shutdown hook. The Java virtual machine shuts downinresponse to two kinds of events:

    The program exitsnormally, when the last non-daemon thread exits or when theexit (equivalently, System.exit) method is invoked, or

    The virtual machine is terminatedin response to a user interrupt, such as typing^C, or a system-wide event, such as user logoff or system shutdown.

    Miscellaneous

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/package-summary.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/package-summary.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executor.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executor.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/package-summary.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html