23
All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25 Tiger: Java 5 Evolutions Dott. Ing. Marco Bresciani

Tiger: Java 5 Evolutions

Embed Size (px)

DESCRIPTION

Alcatel Italy 2006-10-25 - Course held for Wireless Transmission Division, R&D Software Competence Center, Equipment Craft Terminal team.

Citation preview

Page 1: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Tiger: Java 5 Evolutions

Dott. Ing. Marco Bresciani

Page 2: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 2

Introduction

Need improvements from previous Java versions? See this

document:

http://java.sun.com/j2se/JM_White_Paper_R6A.pdf.

All information are taken from

http://java.sun.com/developer/technicalArticles/releases/j2s

e15langfeat/index.html and

http://java.sun.com/developer/technicalArticles/releases/j2s

e50/MigrateToTiger.html and other related pages.

Page 3: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 3

Agenda

http://java.sun.com/reference/tigeradoption/;

Main New Features for the language:

Generics;

Enhanced for loop;

Auto-boxing/un-boxing;

Type-safe enumerations;

static imports;

Other features: metadata, variable arguments, formatted

output, synchronization, …

(http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html)

Page 4: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 4

Overview

enu

m

Meta

data

Gen

erics

stati

c

… for

Boxi

ng

XM

L

Tiger, Tiger burning bright

Like a geek who works all night

What new-fangled bit or byte

Could ease the hacker's weary plight?

Page 5: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 5

Misconceptions About Tiger

Are there any misconceptions about Tiger that you care to

address?

(http://java.sun.com/developer/technicalArticles/Interviews/h

amilton_qa2.html).

One possible misconception is the idea that because this is

such a big release people should delay moving to it. This is

false. Even though this is a big release, we have been careful

to make sure it's very thoroughly tested. Our internal quality

metrics are telling us that Tiger is at a very high quality level.

I'd urge developers to plan for a fast migration to Tiger.

Graham Hamilton, Sun Fellow in the Java Platform Team, Sun

Microsystems.

Page 6: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 6

Generics (Part One)

For further help see

http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf;

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.

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.

Page 7: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 7

Generics (Part Two)

Before the generics:

/**

* Removes 4-letter words from c.

* Elements must be strings

*/

static void expurgate(Collection c) {

for (Iterator i = c.iterator();

i.hasNext(); ) {

if (((String) i.next()).

length() == 4) {

i.remove();

}

}

}

With generics:

/**

* Removes the 4-letter words from

* c

*/

static void expurgate(

Collection<String> c) {

for (Iterator<String> I

= c.iterator();

i.hasNext(); ) {

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

i.remove();

}

}

}

Page 8: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 8

Generics (Part Three)

Runtime Exception!

import java.util.*;

public class Ex1 {

private void testCollection() {

List list = new ArrayList();

list.add(new String("Hello world!"));

list.add(new String("Good bye!"));

list.add(new Integer(95));

printCollection(list);

}

private void printCollection(

Collection c) {

Iterator i = c.iterator();

while(i.hasNext()) {

String item = (String) i.next();

System.out.println("Item: “

+ item);

}

}

public static void main(String argv[]) {

Ex1 e = new Ex1();

e.testCollection();

}

}

Compile error only!

import java.util.*;

public class Ex2 {

private void testCollection() {

List<String> list =

new ArrayList<String>();

list.add(new String("Hello world!"));

list.add(new String("Good bye!"));

list.add(new Integer(95));

printCollection(list);

}

private void printCollection(

Collection c) {

Iterator<String> i = c.iterator();

while(i.hasNext()) {

String item = i.next();

System.out.println("Item: “

+ item);

}

}

public static void main(String argv[]) {

Ex2 e = new Ex2();

e.testCollection();

}

}

Page 9: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 9

Enhanced for Loop (Part 1)

The current for statement is quite powerful and can be used

to iterate over arrays or collections.

However, it is not optimized for collection iteration, simply

because the Iterator serves no other purpose than getting

elements out of the collection.

The new enhanced for construct lets you iterate over

collections and arrays without using Iterators or index

variables.

Page 10: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 10

Enhanced for Loop (Part 2)

This:

void cancelAll(Collection<TimerTask> c) {

for (Iterator<TimerTask> i = c.iterator();

i.hasNext(); )

i.next().cancel();

}

Will become this:

void cancelAll(Collection<TimerTask> c) {

for (TimerTask t : c)

t.cancel();

}

Page 11: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 11

Enhanced for Loop (Part 3)

And this one:

public int sumArray(int

array[]) {

int sum = 0;

for(int i = 0; i < array.length; i++) {

this.sum +=

array[i];

}

return sum;

}

Will also simplify like this:

public int sumArray(int

array[]) {

int sum = 0;

for(int i : array) {

sum += i;

}

return sum;

}

Page 12: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 12

Auto-boxing & Un-boxing (Part 1)

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 un-box the Integer using the intValue method. All of this

boxing and un-boxing is a pain, and clutters up your code. The auto-

boxing and un-boxing feature automates the process, eliminating the

pain and the clutter.

Write this: Integer phoneNumber = (int) Double.parseDouble(phoneNumberText.getText());

Instead of this: Integer phonenumber = new Integer(new Double(Double.parseDouble(phoneNumberText.getText())).intValue());

Page 13: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 13

Auto-boxing & Un-boxing (Part 2)

Consider an int being stored and then retrieved from an ArrayList:

list.add(0, new Integer(59));

int n = ((Integer) (list.get(0))).intValue();

The new auto-boxing/un-boxing feature eliminates this manual

conversion. The above segment of code can be written as:

list.add(0, 59);

int n = list.get(0);

However, note that the wrapper class, Integer for example, must be

used as a generic type:

List<Integer> list = new ArrayList<Integer>();

Page 14: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 14

Type-safe enum (Part 1)

In prior releases, an enumerated type was the int Enum pattern:

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;

This pattern has many problems, such as:

Not type-safe - Since they are just int you can pass in any other int

values.

No namespace - You must prefix constants with a string to avoid collisions

with other int enum types.

Brittleness – They are compile-time constants: if a new constant is added

between two existing ones or the order is changed, clients must be recompiled.

If they are not, they will still run, but their behaviour will be undefined.

Printed values are uninformative - Because they are just ints, if you

print one out all you get is a number, which tells you nothing about what it

represents, or even what type it is.

Page 15: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 15

Type-safe enum (Part 2)

In 5.0, the Java programming language gets linguistic support for

enumerated types. In their simplest form, these enums look just like their

C, C++, and C# counterparts:

enum Season { WINTER, SPRING, SUMMER, FALL }

But appearances can be deceiving. 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.

Page 16: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 16

Type-safe enum (Part 3)

Note that each enum type has a static values method that returns an array

containing all of the values of the enum type in the order they are declared. This

method is commonly used in combination with the for-each loop to iterate over

the values of an enumerated type. Suppose you want to add data and behaviour

to an enum: the idea of adding behaviour to enum constants can be taken one

step further. You can give each enum constant a different behaviour for some

method.

One way to do this by switching on the enumeration constant. 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.

There is another way give each enum constant a different behaviour for some method

that avoids these problems. You can declare the method abstract in the enum type

and override it with a concrete method in each constant. Such methods are known as

constant-specific methods.

So when should you use enums? Any time you need a fixed set of constants. That

includes natural enumerated types as well as other sets where you know all

possible values at compile time, such as choices on a menu, rounding modes,

command line flags, and the like. It is not necessary that the set of constants in

an enum type stay fixed for all time. The feature was specifically designed to

allow for binary compatible evolution of enum types.

Page 17: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 17

Static Imports

To access static members, it is necessary to qualify references

with the class they came from:

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

The static import allows unqualified access without inheriting

from the type containing the static members. Instead, the

program imports the members, either individually or “en

masse”:

import static java.lang.Math.PI;

import static java.lang.Math.*;

Once the static members have been imported, they may be

used without qualification:

double r = cos(PI * theta);

Page 18: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 18

More Features & Enhancements (1)

Concurrency:

The new concurrent package in J2SE

5.0 is dedicated to creating and

managing concurrent threads. This

package provides utilities that will save

you time and trouble creating concurrent

applications.

The Concurrency Utilities packages

provide a powerful, extensible

framework of high-performance

threading utilities such as thread pools

and blocking queues. This package

frees the programmer from the need to

craft these utilities by hand, in much the

same manner the Collections

Framework did for data structures.

Additionally, these packages provide

low-level primitives for advanced

concurrent programming.

Scanner:

The Scanner class uses the regex

package to parse text input and to

convert that input into primitive

types.

Scanner scan = new Scanner(System.in);

System.out.print("What is your name? ");

String name = scan.next();

System.out.print("How old are you? ");

int age = scan.nextInt();

String msgPattern = "Hi {0}. You are {1}

years old.";

String msg =

MessageFormat.format(msgPattern,

name, age);

System.out.println(msg);

Page 19: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 19

More Features & Enhancements (2)

Varargs (Variable Arguments):

In past releases, a method that took an

arbitrary number of values required you

to create an array and put the values

into the array prior to invoking the

method. The varargs feature automates

and hides the process and it is upward

compatible with pre-existing APIs.

public static String format(

String pattern,

Object... arguments);

The three periods after the final

parameter's type indicate that the final

argument may be passed as an array or

as a sequence of arguments. Varargs

can be used only in the final argument

position.

Metadata (Annotations):

The Java platform has always had

various ad hoc annotation mechanisms.

For example the @deprecated javadoc

tag is an ad hoc annotation indicating

that the method should no longer be

used.

As of release 5.0, the platform has a

general purpose annotation (also known

as metadata) facility that permits you to

define and use your own annotation

types. The facility consists of a syntax for

declaring annotation types, a syntax for

annotating declarations, APIs for

reading annotations, a class file

representation for annotations, and an

annotation processing tool.

Page 20: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 20

Where to Get More Information (1)

Java Programming Language:

http://java.sun.com/j2se/1.5.0/docs/guide/language/;

JDK 5.0 Documentation: http://java.sun.com/j2se/1.5.0/docs/;

New Features and Enhancements JSE 5.0:

http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html;

The All-New Java 2 Platform, Standard Edition (J2SE) 5.0 Platform:

Programming with the New Language Features in J2SE 5:

http://java.sun.com/developer/technicalArticles/releases/j2se15langfe

at/;

JSE 5.0 in a Nutshell:

http://java.sun.com/developer/technicalArticles/releases/j2se15/;

What’s New in JavaDoc 5.0:

http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-

1.5.0.html.

Page 21: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 21

Where to Get More Information (2)

JSE 5.0: http://java.sun.com/j2se/1.5/index.jsp;

J2SE 5.0 Adoption: http://java.sun.com/reference/tigeradoption/;

JavaDoc – The Java API Documentation Generator:

http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html;

How and When To Deprecate API:

http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/deprecation/depr

ecation.html;

How to Write Doc Comments for JavaDoc:

http://java.sun.com/j2se/javadoc/writingdoccomments/index.html;

Java Language Specification:

http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf;

The Java Tutorial (ATTENTION: it’s based on Java 6!):

http://java.sun.com/docs/books/tutorial/;

Page 22: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 22

Answer to Life, the Universe and

Everything

Any Question?Any Question?

Page 23: Tiger: Java 5 Evolutions

All rights reserved © 2005, Alcatel Tiger: Java 5 Evolutions / 2006-10-25

Page 23

www.alcatel.com