j2se 5 features

50
What is new in Java 5?

Upload: naveen-jain

Post on 07-Apr-2018

228 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 1/50

What is new in Java 5?

Page 2: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 2/50

static imports

enhanced for loop

variable argument methods

assertions (1.4 )Generics

enumerations

Auto boxing / unboxing

Page 3: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 3/50

� Used to import static members of a class

� After import they can be referred directly

eg :import static java.lang.System.out;

import static java.lang.Integer.*;

 public class TestStaticImport {

 public static void main(String[] args) {

out.println(MAX_VALUE);out.println(toHexString(42));

}

}

static imports

Objective 7.1

Page 4: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 4/50

� Specialized loop for array or collection

� similar to for-each in some languages

� format :

for(declaration : expression)

� declaration : newly created block variable whose type

is compatible with the elements of the array

� expression : must evaluate to array or collection

enhanced for loop

Objective 2.2

Page 5: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 5/50

example

then

int a[ ] = {10, 20, 30, 40, 50};

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

System.out.println(a[i]);

now

int a[ ] = {10, 20, 30, 40, 50} ;

for(int i : a)

System.out.println(i);

enhanced for loop

Objective 2.2

Page 6: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 6/50

Legal µfor¶ loops

Long [ ] La = {4L, 5L, 6L};

long [ ] la = {7L, 8L, 9L};

int [ ][ ] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}};

String [ ] sNums = {"one", "two", "three"};Animal [ ] animals = {new Dog(), new Cat()};

for(long y : la ) ; // loop thru an array of longs

for(long lp : La) ; // autoboxing the Long objects into longs

for(int[] n : twoDee) ; // loop thru the array of arrays

for(int n2 : twoDee[2]) ; // loop thru the 3rd sub-arrayfor(String s : sNums) ; // loop thru the array of Strings

for(Object o : sNums) ; // set an Object reference to each String

for(Animal a : animals) ; // set an Animal reference to each element

enhanced for loop

Objective 2.2

Page 7: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 7/50

Illegal µfor¶ loops

int x2;

long [ ] la = {7L, 8L, 9L};

int [ ][ ] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}};

Animal [ ] animals = {new Dog(), new Cat()};

for(x2 : la) ; // x2 is already declared

for(int x2 : twoDee) ; // can't stuff an array into an int

for(int x3 : la) ; // can't stuff a long into an int

for(Dog d : animals) ; // you might get a Cat!

enhanced for loop

Objective 2.2

Page 8: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 8/50

also known variable-arity method

method is invoked with variable number of arguments

 Not as flexible as in C++

format :

methodname(other parameters, <type> «<variable>)

<variable> is implicitly an array variable argument should be at the end

Overloading can be done (with no ambiguity)

Var arg methods

Objective 2.3

Page 9: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 9/50

Page 10: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 10/50

Example

static void vaTest(int ... v) {

}

static void vaTest(int s, int ... v) { // ambiguous

}

static void vaTest(boolean « v) {}

 public static void main(String args[])

{

vaTest(); //ambiguous method call}

Var arg methods

Objective 2.3

Page 11: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 11/50

� Assertions are used to test assumptions

� Can be enabled or disabled at runtime

� assert is keyword from ver 1.4

� If assumption fails AssertionError is thrown

� AssertionError is subclass of  Error with nomethods

Assertions

Objective 2.3

Page 12: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 12/50

Formats

� assert condition

� assert condition : expression

Assertions

Objective 2.3

Page 13: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 13/50

example 1

public static void main(String args[]) {

int n;

for(int i=0; i < 10; i++) {

n = getnum();

assert n > 0 ; // will fail with n is 0

System.out.println("n is " + n);}

}

}

Assertions

Objective 2.3

Page 14: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 14/50

example 2

public static void main(String args[]) {

int n;

for(int i=0; i < 10; i++) {

n = getnum();

assert n > 0 : ³n is not positive´ // Display this message

System.out.println("n is " + n);

}

}

}

Anyexpression

that has a

value

Assertions

Objective 2.3

Page 15: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 15/50

� If assert is used as identifier in old

 programs, it is a problem (oops!)

�  No worry ! Just inform the compiler whichcompiles with warning

  javac -source 1.3 MyCode.java

  javac -source 1.4 MyCode.java

  javac -source 1.5 MyCode.java

  javac -source 5 MyCode.java

Assertions

Objective 2.3

Page 16: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 16/50

Enabling / Disabling assertions

  java -ea MyCode

  java -ea pack.MyCode

  java -enableassertions MyCode

  java -da MyCode  java -disableassertions MyCode

  java -ea -da:Test2 MyCode // disable only for Test2

  java -da:myPackage MyCode// disable for all classes of myPackage

  java -da:myPackage« MyCode // disable for myPackage and sub packages

  java -esa MyCode // enable for system classes// other flags for system classes -dsa

-enablesystemassertions

-disablesystemassertions

Assertions are

disabled by default

Assertions

Objective 2.3

Page 17: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 17/50

Using assertions appropriately

Do not use assertions

 ± to validate arguments of public methods

 ± to validate command line arguments ± that can cause side effects (to do something which is required even

when assertions are disabled)

eg : assert(x=gotIt()); // what if ±da is used ?

Use assertions

 ± to validate arguments of private methods

 ± to check cases that should never happen (like switch default)

Assertions

Objective 2.3

Page 18: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 18/50

Legacy way of using collections

creationList myList = new ArrayList(); // can't declare a type

myList.add("Fred"); // OK, it will hold Strings

myList.add(new Dog()); // and it will hold Dogs too

myList.add(new Integer(42)); // and Integers...

retrieval

String s = (String) myList.get(0); // goes fineString s = (String) myList.get(1) ; // OOPS !!! ClassCastException

Generics

Objective 6.3 6.4

legacy collections

are nottype safe

Page 19: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 19/50

Generic collections (java 5)creation

List<String> myList = new ArrayList<String>( ); // takes only Strings

myList.add("Fred"); // goes finemyList.add(new Dog()); // No !! compiler does not allow

myList.add(new Integer(42)); // sorry again

retrieval

String s = myList.get(0); // no casting required. Compiler knows it

Generics

Objective 6.3 6.4

Page 20: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 20/50

method parametersLegacy

void checkAndRemove(Collection c) {

String s = null;

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

s = (String) i.next( );

if (s.length( ) > 4)

System.out.println(s);}

}

Generic

void checkAndRemove(Collection <String> c) {

String s = null;

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

s = i.next( );if ( s.length( ) > 4)

System.out.println(s);

}

}

Generics

Objective 6.3 6.4

Page 21: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 21/50

return types

 public Set<Dog> getDogList() {Set<Dog> dogs = new HashSet<Dog>();

«««««.

return dogs;

}

Dog d = getDogList().get(0); //no need to cast

Generics

Objective 6.3 6.4

Page 22: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 22/50

Generic using non-genericList<Integer> myList = new ArrayList<Integer>();

myList.add(6);

Adder adder = new Adder();

int total = adder.addAll(myList);

//The older, non-generics class we want to use:

class Adder {

int addAll(List list) {

Iterator it = list.iterator();

int total = 0;

while (it.hasNext()) {int i = ((Integer)it.next()).intValue();

total += i;

}

return total;

}

}

Generics

Objective 6.3 6.4

Adder class compiles fine

as the method is not

changing the list

Page 23: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 23/50

Generic using non-genericList<Integer> myList = new ArrayList<Integer>();

myList.add(4);

myList.add(6);

Inserter in = new Inserter();

in.insert(myList);

class Inserter {

// method with a non-generic List argument

void insert(List list) {

list.add(new Integer(42)); // adds to the incoming list}

}

Generics

Objective 6.3 6.4

Inserter class compiles with warning as the

method is changing the list javac Inserter.java

 Note: Inserter.java uses unchecked or unsafe operations.

 Note: Recompile with -Xlint:unchecked for details.

Page 24: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 24/50

Generics & polymorphism

class Parent { }

class Child extends Parent { }

List<Parent> myList = new ArrayList<Child>();

Generics

Objective 6.3 6.4

Does not work as

ArrayList<child>

is not a

subclass of 

List<Parent>

Compiler checks for

Exact match

Page 25: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 25/50

Generics & polymorphism

List<Dog> dog = new ArrayList<Dog>( );

addIt(dog);

void addIt(List<Animal> a) {

«««.

}

Generics

Objective 6.3 6.4

Does not work ! !

List<Dog>

cannot be assigned

to

List<Animal>

Page 26: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 26/50

Wildcard <?>� Used to declare generic subtypes

Bounded wildcard

List <? extends Animal> a = new ArrayList<Animal>( );

List <? extends Animal> a = new ArrayList<Dog>( );

List <? extends Animal> a = new ArrayList<Cat>( );

� Takes List of Animal or any subtype of Animal� But objects cannot be added

a.add(new Dog( ) ); //fails

a.add(new Animal() ); //fails

Generics

Objective 6.3 6.4

Page 27: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 27/50

Wildcard <?>Lower Bounded wildcard

List <? super Dog> a = new ArrayList<Animal>( );

List <? super Dog> a = new ArrayList<Object>( );

List <? super Dog> a = new ArrayList<Dog>( );

� Takes List of Dog or any super type of Dog

� Allows adding Dog objects

Generics

Objective 6.3 6.4

Page 28: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 28/50

Wildcard <?>

List<?> indicates any object

same as List<? extends Object>

Generics

Objective 6.3 6.4

Page 29: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 29/50

Wildcard <?>

Check out !!!

List<?> list = new ArrayList<Dog>(); // valid

List<? extends Animal> a

List = new Array

List<Dog>(); // valid

List<?> foo = new ArrayList<? extends Animal>(); //wrong! should be on the

left side

List<? extends Dog> cList = new ArrayList<Integer>(); //not valid

List<? super Dog> bList = new ArrayList<Animal>(); //valid. But only Dog

objects can be added

List<? super Animal> dList = new ArrayList<Dog>(); // not valid

Generics

Objective 6.3 6.4

Page 30: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 30/50

Generic class declaration

class Box<T> {

private T t;

public void add(T t) {

this.t = t;

}

public T get() {

return t;

}

public static void main(String[] args) {

Box<Dog> box = new Box<Dog>();

box.add(new Dog( ) );

}

}

Generics

Objective 6.3 6.4

Page 31: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 31/50

Generic class declaration

 public class AnimalHolder<T extends Animal> { // use "T" instead of "?³

T animal;

 public static void main(String[] args) {

AnimalHolder<Dog> dogHolder = new AnimalHolder<Dog>(); // OK 

AnimalHolder<Integer> x = new AnimalHolder<Integer>(); // NO!

}

}

Generics

Objective 6.3 6.4

Page 32: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 32/50

Generic methods

 public <T> void makeArrayList(T t) {

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

list.add(t);

}

 public <T extends Animal> void makeArrayList(T t) {

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

list.add(t);

}

Generics

Objective 6.3 6.4

Page 33: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 33/50

� In prior releases, enumerated types were simulated

using static final which were not type safe

� enums added in release 5.0

� enum is a type with a set of constant values

� enums implemented as class

Enums

Objective 1.3

Page 34: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 34/50

enum Season {WINTER, SPRING, SUMMER, FALL}

Season sea = Season.WINTER;

switch(sea) {case WINTER :

case SUMMER :

«««

}

for (Season x : Season.values() )

System.out.println(x);

Enums

Objective 1.3

Page 35: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 35/50

what goes on inside ?

creates a class Season with

static final variables WINTER, SPRING etc

static method values() which returns an array static method valueOf(String) that returns appropriate enum

value

other methods like equals(), hashCode(), toString() etc

The class implements Comparable<Season> and Serializable

Enums

Objective 1.3

Page 36: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 36/50

Constructors, methods and variables

enum Size {

SMALL(21), MEDIUM(35), BIG(45) ;

Size(int s) {

measure = s;

}private int measure;

public int getSize() {

return measure;

}

}

Size size;

size = Size.BIG;

System.out.println(size.getSize()); // prints 45

Enums

Objective 1.3

Page 37: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 37/50

Enums

Objective 1.3

Read on to know more «

Constructors can be overloaded

Constructors can never be invoked directly

enums can be inside or outside the class

enums cannot be defined in a method (local enums)

Semicolon at the end of enum declaration is optional

Page 38: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 38/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

wrapper classes

Designed to convert primitives into objects

Wrapper objects are immutable

provide functions for conversion of primitives to/from String objectsto different bases

All wrapper class names map to primitives they represent except

Integer and Character

Byte, Short, Integer, Long, Float, Double are sub classes of Number

constructors overloaded to take primitives as well as their Stringrepresentation

Page 39: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 39/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Methods of Number

byte byteValue( )

short shortValue( )

int intValue( )

long longValue( )float floatValue( )

double doubleValue( )

Character

char charValue( )

Boolean

boolean booleanValue( )

Page 40: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 40/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Similar Methods of Numeric wrappers

static xxx parseXxx(String)

convert String to primitive (only numerics)

may throw NumberFormatException

static xxx parseXxx(String s, int radix)

overloaded method for integer family

String toString( )

static String toBinaryString( n )

static String toOctalString( n )

static String toHexString( n ) } Only Integer & Long

Page 41: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 41/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Boxing / Unboxing Before Java 5, wrapping and unwrapping was done explicitly

For example to perform arithmatic on a wrapped value involved

unwrapping and re-wrapping after operation

Integer x = new Integer(45);int y = x.intValue( );

y = y + 1 0 ;

x = new Integer(y) ;

 java 5 provides auto boxing / unboxing

In that wrapping and unwrapping done automatically based on theoperation

Integer x = new Integer(45);

x = x +10 ;

x++; // and so on

Page 42: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 42/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

All these are possible now !!!

Integer x = 36; // wrap it

x++; // unwrap and re-wrap

List l = new ArrayList();

l.add(0,36); //wrap and add

Integer a = 30; //wrap

Integer b = 20; //wrap

Integer c = a + b; //unwrap, add, wrap the sum

if (a.equals(30) ) //unwrap and compare

Page 43: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 43/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

== vs equals( )

equals ( ) : true if the values wrapped are same

== : true if object references are same

=== : true in the following

two Boolean objects with same value

two Byte objects with same value

two Character objects with same value upto 127

two Short and Integer with same value -128 to 127

Page 44: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 44/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class AddBoxing {

static void go(Integer x) { System.out.println("Integer"); }

static void go(long x) { System.out.println("long"); }

 public static void main(String [] args) {

int i = 5;

go(i); // which go() will be invoked?

}

}

output

Widening

 preferred over  boxing

long

Page 45: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 45/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class AddVarargs {

static void go(int x, int y) { System.out.println("int,int");}

static void go(byte... x) { System.out.println("byte... "); }

 public static void main(String[] args) {

 byte b = 5;

go(b,b); // which go() will be invoked?

}}

output

Widening

 preferred over vararg methods

int,int

Page 46: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 46/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class BoxOrVararg {

static void go(Byte x, Byte y) { System.out.println("Byte, Byte"); }

static void go(byte... x) { System.out.println("byte... "); }

 public static void main(String [] args) {

 byte b = 5;

go(b,b); // which go() will be invoked?

}}

output

Boxing

 preferred over vararg methods

Byte, Byte

Page 47: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 47/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class Dog4 {

 public static void main(String [] args) {

Dog4 d = new Dog4();

d.test(new Integer(5));

}

void test(Long x) { }

}

 No way !!

Page 48: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 48/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class WidenAndBox {

static void go(Long x) { System.out.println("Long"); }

 public static void main(String [] args) {

 byte b = 5;

go(b);

}

}

 Not possible !!

widen and boxillegal

Page 49: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 49/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues

class BoxAndWiden {

static void go(Object o) {

Byte b2 = (Byte) o;

System.out.println(b2);

}

 public static void main(String [] args) {

 byte b = 5;go(b);

}

}

Possible !!

Box and widen

Page 50: J2SE 5 Features

8/6/2019 J2SE 5 Features

http://slidepdf.com/reader/full/j2se-5-features 50/50

Wrapper classes ± Boxing/Unboxing

Objective 3.1

Overloading issues - SUMMARY

.

You CANNOT widen from one wrapper type to another. (IS-A fails)

You CANNOT widen and then box. (An int can't become a Long)

You can box and then widen. (An int can become an Object, via

Integer)

You can combine var-args with either widening or boxing