Sie sind auf Seite 1von 50

What is new in Java 5?

static imports enhanced for loop variable argument methods assertions (1.4 ) Generics enumerations Auto boxing / unboxing

static imports
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)); } }
Objective 7.1

enhanced for loop


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
Objective 2.2

enhanced for loop


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);
Objective 2.2

enhanced for loop


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 ) ; for(long lp : La) ; for(int[] n : twoDee) ; for(int n2 : twoDee[2]) ; for(String s : sNums) ; for(Object o : sNums) ; for(Animal a : animals) ; // loop thru an array of longs // autoboxing the Long objects into longs // loop thru the array of arrays // loop thru the 3rd sub-array // loop thru the array of Strings // set an Object reference to each String // set an Animal reference to each element

Objective 2.2

enhanced for loop


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) ; for(int x2 : twoDee) ; for(int x3 : la) ; for(Dog d : animals) ;

// x2 is already declared // can't stuff an array into an int // can't stuff a long into an int // you might get a Cat!

Objective 2.2

Var arg methods


 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)
Objective 2.3

Var arg methods


 Example : static void vaTest(int ... v) { for(int x : v) System.out.print(x); } static void vaTest(String s, int ... v) { System.out.println(s); for(int x : v) System.out.print(x ); } public static void main(String args[]) { vaTest(1,2); vaTest(new int[]{4,5,6}); int b[] = {100,200,300}; vaTest("Hello", 1,2,3,4,5); vaTest("Hello",b); vaTest(); }

Objective 2.3

Var arg methods


Example static void vaTest(int ... v) { } static void vaTest(int s, int ... v) { } static void vaTest(boolean v) { }

// ambiguous

public static void main(String args[]) { vaTest(); //ambiguous method call }

Objective 2.3

Assertions
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 no methods
Objective 2.3

Assertions
Formats assert condition assert condition : expression

Objective 2.3

Assertions
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); } } }


Objective 2.3

Assertions
example 2 public static void main(String args[]) { int n; for(int i=0; i < 10; i++) { n = getnum();

Any expression that has a value

assert n > 0 : n is not positive // Display this message System.out.println("n is " + n); } } }
Objective 2.3

Assertions
If assert is used as identifier in old programs, it is a problem (oops!) No worry ! Just inform the compiler which compiles with warning
javac javac javac javac -source 1.3 MyCode.java -source 1.4 MyCode.java -source 1.5 MyCode.java -source 5 MyCode.java

Objective 2.3

Assertions
Enabling / Disabling assertions java -ea MyCode java -ea pack.MyCode java -enableassertions MyCode Assertions are java -da MyCode disabled java -disableassertions MyCode by default 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
Objective 2.3

Assertions
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)

Objective 2.3

Generics
Legacy way of using collections
creation
List myList = new ArrayList(); // can't declare a type legacy collections myList.add("Fred"); // OK, it will hold Strings are not myList.add(new Dog()); // and it will hold Dogs too type safe myList.add(new Integer(42)); // and Integers...

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

Objective 6.3 6.4

Generics Generic collections (java 5)


creation
List<String> myList = new ArrayList<String>( ); // takes only Strings myList.add("Fred"); // goes fine myList.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

Objective 6.3 6.4

Generics
method parameters
Legacy 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); } }

Objective 6.3 6.4

Generics
return types

public Set<Dog> getDogList() { Set<Dog> dogs = new HashSet<Dog>(); . return dogs; } Dog d = getDogList().get(0); //no need to cast
Objective 6.3 6.4

Generics
Generic using non-generic
List<Integer> myList = new ArrayList<Integer>(); myList.add(6); Adder adder = new Adder(); int total = adder.addAll(myList);

Adder class compiles fine as the method is not changing the list

//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; } }

Objective 6.3 6.4

Generics
Generic using non-generic
List<Integer> myList = new ArrayList<Integer>(); myList.add(4); Inserter class compiles with warning as the myList.add(6); method is changing the list Inserter in = new Inserter(); javac Inserter.java in.insert(myList); Note: Inserter.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

class Inserter { // method with a non-generic List argument void insert(List list) { list.add(new Integer(42)); // adds to the incoming list } }

Objective 6.3 6.4

Generics
Generics & polymorphism
class Parent { } class Child extends Parent { } List<Parent> myList = new ArrayList<Child>();
Does not work as ArrayList<child> is not a subclass of List<Parent> Compiler checks for Exact match
Objective 6.3 6.4

Generics
Generics & polymorphism
List<Dog> dog = new ArrayList<Dog>( ); addIt(dog);

void addIt(List<Animal> a) { . }

Does not work ! ! List<Dog> cannot be assigned to List<Animal>

Objective 6.3 6.4

Generics
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
Objective 6.3 6.4

Generics
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

Objective 6.3 6.4

Generics
Wildcard <?>

List<?>

indicates any object

same as List<? extends Object>

Objective 6.3 6.4

Generics
Wildcard <?> Check out !!!
List<?> list = new ArrayList<Dog>(); // valid List<? extends Animal> aList = new ArrayList<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

Objective 6.3 6.4

Generics
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( ) ); } }
Objective 6.3 6.4

Generics
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! } }

Objective 6.3 6.4

Generics
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); }

Objective 6.3 6.4

Enums
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
Objective 1.3

Enums
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);
Objective 1.3

Enums
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

Objective 1.3

Enums
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
Objective 1.3

Enums
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

Objective 1.3

Wrapper classes Boxing/Unboxing


wrapper classes
Designed to convert primitives into objects Wrapper objects are immutable provide functions for conversion of primitives to/from String objects to 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 String representation

Objective 3.1

Wrapper classes Boxing/Unboxing


Methods of Number byte byteValue( ) short shortValue( ) int intValue( ) long longValue( ) float floatValue( ) double doubleValue( ) Character char charValue( ) Boolean boolean booleanValue( )
Objective 3.1

Wrapper classes Boxing/Unboxing


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


Objective 3.1

Wrapper classes Boxing/Unboxing


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 +10 ; x = new Integer(y) ; java 5 provides auto boxing / unboxing In that wrapping and unwrapping done automatically based on the operation Integer x = new Integer(45); x = x +10 ; x++; // and so on Objective 3.1

Wrapper classes Boxing/Unboxing


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
Objective 3.1

Wrapper classes Boxing/Unboxing


== 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

Objective 3.1

Wrapper classes Boxing/Unboxing


Overloading issues
class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } Widening static void go(long x) { System.out.println("long"); } preferred over

boxing
public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } } output

long
Objective 3.1

Wrapper classes Boxing/Unboxing


Overloading issues class AddVarargs { static void go(int x, int y) { System.out.println("int,int");} Widening 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

preferred over vararg methods

int,int
Objective 3.1

Wrapper classes Boxing/Unboxing


Overloading issues class BoxOrVararg { static void go(Byte x, Byte y) { System.out.println("Byte, Byte"); } Boxing 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

preferred over vararg methods

Byte, Byte
Objective 3.1

Wrapper classes Boxing/Unboxing


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 !!

Objective 3.1

Wrapper classes Boxing/Unboxing


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 box illegal

Objective 3.1

Wrapper classes Boxing/Unboxing


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); } }
Objective 3.1

Possible !! Box and widen

Wrapper classes Boxing/Unboxing


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

Objective 3.1

Das könnte Ihnen auch gefallen