Presentation is loading. Please wait.

Presentation is loading. Please wait.

J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.

Similar presentations


Presentation on theme: "J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger."— Presentation transcript:

1 J2SE 5.0 New Features

2 J2SE 5.0 aka JDK 1.5 aka Tiger

3 What’s New J2SE 5.0 is full of dramatic changes to the java programming language, including new syntax support and JVM enhancements. It is considered to be the most revolutionary java release since JDK1.2

4 Today Generics Enhanced for Loop Autoboxing \ Unboxing Typesafe Enums Varargs Static Imports

5 For Each Statement A great way to ditch annoying Iterators. Makes code more elegant and less error prone. before after

6 Spot the Bug

7 Fixed Version

8 Using the For Each Statement

9 Iterating an Array The for-each construct can be used to iterate arrays, hiding the index variable instead of the iterator:

10 The Iterable Interface To make your own classes work with this construct you should implement the Iterable interface:

11 Autoboxing and Unboxing Autoboxing: –Automatic converting of primitives into wrapper classes Integer x = 10; Unboxing –Automatic converting of wrapper classes into primitives double PI = new Double(3.14);

12 Autoboxing and Unboxing for (Integer i = 0;i < new Integer(10);) { i++; } Boolean b1 = true; Boolean b2 = true; Boolean b3 = false; Boolean result = (b1 || b2) && b3;

13 Example

14 Enums Previously, the standard way to represent an enumerated type was to use the int Enum pattern: public static final int WINTER = 0; public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3;

15 The int Enum Pattern - Problems Not TypeSafe –you could add seasons or pass an arbitrary season NoNamespace –With other enum types Uninformative printed values Can not add methods to enum values

16 The TypeSafe Enum Pattern Create a class with a private constructor. Each enum value is a public static final instance of the class. Major problem – cannot be used with switch statements.

17 Java 1.5 Enums enum Season{ WINTER, SPRING, SUMMER, FALL } Using the enum… if (type == Season.WINTER) System.out.println (…)

18 Java Enums are powerful features You can add arbitrary methods and fields to enum types, implement interfaces, and enjoy the existing implementation of the Object class methods. Enums are Comparable and Serializable

19 Adding data to Enums

20 The enum type can be declared with a constructor, and each enum constant is declared with parameters to be passed to the constructor.

21 Adding Behavior to Enum Constants Using switch statements

22 Convert Switch statement to polymorphism

23 Enums Enums are classes that extend java.lang.Enum. Each declared value is an instance of the enum. Enum values are public, static and final. Enums can be compared with == or equals(). Implement several methods, ordinal(), compareTo(), valueOf()

24 Varargs In past releases, if you wanted a method to get an arbitrary number of arguments, it should have been defined to receive an array. Alternatively you would have created several overloaded methods. Tiger allows variable length argument list for its methods, providing cleaner code with less overloaded methods.

25 Varargs Varargs is done with the … operator. Example. The following constructor public Person (String name, String details… ) Can be called with many different invocations: new Person (“Alexander ”); new Person (“Alexander ”, “Bell ”); new Person (“Alexander ”,”Graham”, “Bell ”);

26 Varargs Accessing the varargs is done like accessing arrays public int sum (int... numbers) { int result = 0; for (int i = 0;i < numbers.length;i++) { result+= numbers[i]; } return result; } Varargs can be used only in the final argument position.

27 Varargs Before: print( new String[] { “1”, “2”, “3” } );... private static void print( String[] array ) { for ( int j = 0; j < array.length; j++ ) { System.out.println( array [ j ] ); } } After : print( “1”, “2”, “3”, “4” ); // put as many as you need... private static void print( String... array ) { System.out.println ( array.length ); for ( String s : array ) { System.out.println( s ); // same as array[ j ] } }

28 Static Imports In order to access static members, it is necessary to qualify references with the class they came from. double r = Math.cos(Math.PI * theta); As a workaround people often put static members as part of an interface and inherit from that interface. This is known as the “Constant Interface Antipattern”

29 Static Imports Using constants of another class is merely an implementation detail. Declaring that a class implements an interface is an API issue. Implementation details should not leak into APIs. The static import construct allows you to access static members of another class without inheriting from the type containing them.

30 Static Imports members of another class are imported import static java.lang.Math.PI; Once imported they can be used without qualification double r = cos(PI * theta);

31 Example Before System.out.println(“Hello”); System.out.println(“World”); System.err.println(“From”); System.err.println(“Me”); After import static java.lang.System.*; out.println(“Hello”); out.println(“World”); err.println(“From”); err.println(“Me”);

32 Static Vs. Normal import Static imports are analogous to regular imports. In normal imports you import classes from packages, and in static imports you import static class members out of classes. Use with care: only when frequent access is required. It is suppose to improve readability, and overuse may have an opposite effect.

33 Generics Generic Types have been widely anticipated by the java community. The first place to see their use is in the collections API. With Generics you can provide common functionality with Type-safe Lists, Maps and Iterators for different java types. Parameterized Types can also be defined as return types and arguments. You can also write your own generic types.

34 Before Tiger Adding a String to a List Must use casting to extract the String Potential ClassCastException List list = new ArrayList(); list.add(new String(“Hello”); list.add(new Integer(1)); list.add(new ArrayList()); String s = (String) list.get(0); String s = (String) list.get(1);

35 Generics With Tiger With Generics you construct real homogenous collections. Extracting the contents no longer requires casting List list = new ArrayList (); list.add(“One”); list.add(“Two”); list.add(“Three”); String one = list.get(0);

36 Generics Using casting the programmer is prone to a run time error. With generics the programmer can express his intent to have a homogenous data type. In the example the list was a generic interface that took String as a type parameter. The significant difference is that now the compiler can assure the type correctness at compile time. we get improved robustness of our code.

37 Parameterized types as Arguments public void foo( List names)

38 Parameterized types as return types public List getNames();

39 Parameterized types as parameter types public void bar (Map >> map);

40 Defining Simple Generics

41

42 Invocation of Generic Types List = new LinkedList (); You may imagine that List stands for a version of List where E has been replaced by Integer: public interface IntegerList { void add(Integer x) Iterator iterator(); } This intuition is helpful, but also misleading.

43 Generics Vs. C++ Templates In java Generics, there is no real expansion of code per type invocation. There are no multiple copies of the code, not in source, not in binary, and not in memory. A generic type declaration is compiled once, and turned into a class file, just like any ordinary class or interface declaration.

44 Generics and Subtyping Is the following code legal? List sList = new ArrayList (); List oList = stringList; Is a list of Strings also A list of Objects? oList.add(new Object()); String string = sList.get(0); // attempt to assign an Object to a String Compile time Error

45 Generics and Subtyping Rule – if B is a subtype of A and G is some generic type declaration then G is not a subtype of G This is probably the most counter intuitive rule of generics.

46 Wildcards – The need Consider a method that prints all the elements of a collection. old version first Attempt with generics But this version will not work with all Collections, Only with Collection which is not a super type of all collections

47 WildCards The super type of all collections is noted as Collection, pronounced “collection of unknown”

48 Bounded Wildcards What if we want to pass List instead of List

49 Upper Bound of the Wildcard We say that the method receives a list of unknown type that extends shape. Shape is the upper bound of the wildcard.

50 Generic Methods Consider a method that takes an object array and a collection, and inserts all elements of the array into the collection. First attempt:

51 Generic Methods Just like type declarations, method declarations can be generic. Generic Methods are methods parameterized by one or more type parameter.

52 Generic Methods We don’t pass the actual type argument to the method. It is inferred by the compiler based on the most specific type argument that will make the call type-correct.

53 Generic Methods For Polymorphic method invocations, i.e. If the return type or other method arguments are not effected by the type parameter T, wildcards should be preferred. Type variables can have upper bounds too! Wildcards support flexible subtyping

54 Generic Methods Use generic methods when you wish to express dependencies among the argument types or return types. Generic methods and wildcards can also be used in tandem.

55 Interoperating with existing code How can legacy code and generic code work together? When a generic type is used without a type parameter, it’s called a raw type. There are many interesting implications of combining generic and legacy code. Not in today's scope.

56 Erasure and Translation Aliasing a generic list with a raw list. At runtime the code acts like this Both versions will end with a ClassCastException.

57 Erasure and Translation Generics are implemented as a front-end conversion called erasure. The generic version is converted into a non generic version. All uses of type variables are replaced with upper bound of the type variable, and whenever the resulting code is not type correct, a cast is inserted. As a result, the type safety of the Java Virtual Machine are never at risk, even in the presence of unchecked warnings.

58 A Generic class is Shared by all its Invocations List l1 = new ArrayList (); List l2 = new ArrayList (); System.out.println(l1.getClass() == l2.getClass()); Returns True!!!

59 Casts and instanceOf You cannot ask an instance if it is an instance of a particular type The runtime system will not check casts such as

60 Lower bounded Wildcards Suppose you create a TreeSet of Strings. TreeSet. We need to pass it a comparator that compares strings. But a comparator that compares Objects will also do. In fact any super class of String is fine to use. Solution: lower bounded wildcards

61 Lower bounded Wildcards Consider a method that returns the maximal element in a collection. The elements should be comparable, and specifically to each other (to the collection type). First Attempt:

62 Lower bounded Wildcards But consider the following class: All elements in the collection are comparable to each other, but the inferred type must be Foo, which does not implement Comparable T does not have to be comparable exactly to itself, it is only required that it is comparable to one of its superclasses.

63 Bounding Rules If the API only uses a type parameter as an argument you should take advantage of lower bounded wildcards (? super T) If the API only returns T, clients will enjoy the flexibility if you provide them upper bounded wildcards (? extends T)

64 Converting Existing Code to Generics Naïve conversions may unintentionally modify the API contract. Notice that the non generic version of containsAll could work with any collection, while the generic one will not. Should the argument type be restricted? Could we pass a collection of a subtype of E? In the case of addAll we should assure that the method works with a collection containing sub types of E

65 Converting Existing Code to Generics Recall the Collections.max() method But the erasure of this method is Which is different then the original signature of max()

66 Giving multiple bounds for a type parameter Using the Syntax T1 & T2 & … Tn, a type variable is assigned with multiple bounds and is known to be a subtype of all the listed types. The first type mentioned in the bound is used as the erasure of the type variable.

67 More Features Annotations Overriding methods return types. (Covariant Typing) printf-like formatting methods. New default Java look & feel. Parallel GC by default on server machines Class Data Sharing (CDS) Threading issues are boosted in Tiger.

68 Getting Started Get a J2SE 5.0 supported IDE: –NetBeans 4.0 –IDEA IntelliJ 4.5 –“Cheetah” – eclipse 3.0 plugin


Download ppt "J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger."

Similar presentations


Ads by Google