Tiger: Java 5 Evolutions

431 views

Published on

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

Published in: Technology, News & Politics
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
431
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Tiger: Java 5 Evolutions

  1. 1. Tiger: Java 5 Evolutions Dott. Ing. Marco Bresciani Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  2. 2. Introduction Page 2 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  3. 3. Agenda Page 3 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) Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  4. 4. Overview Page 4 Tiger, Tiger burning bright Like a geek who works all night What new-fangled bit or byte Could ease the hacker's weary plight? Boxi ng stati c XM L Tiger: Java 5 Evolutions / 2006-10-25 … for Gen enu erics m Meta data … All rights reserved © 2005, Alcatel
  5. 5. Misconceptions About Tiger Page 5 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  6. 6. Generics (Part One) Page 6 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  7. 7. Generics (Part Two) Page 7 Before the generics: With 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(); } } } /** * 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(); } } } Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  8. 8. Generics (Part Three) Page 8 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(); } } Tiger: Java 5 Evolutions / 2006-10-25 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(); } } All rights reserved © 2005, Alcatel
  9. 9. Enhanced for Loop (Part 1) Page 9 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  10. 10. Enhanced for Loop (Part 2) Page 10 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(); } Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  11. 11. Enhanced for Loop (Part 3) Page 11 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; } Tiger: Java 5 Evolutions / 2006-10-25 Will also simplify like this: public int sumArray(int array[]) { int sum = 0; for(int i : array) { sum += i; } return sum; } All rights reserved © 2005, Alcatel
  12. 12. Auto-boxing & Un-boxing (Part 1) Page 12 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 autoboxing 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()); Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  13. 13. Auto-boxing & Un-boxing (Part 2) Page 13 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>(); Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  14. 14. Type-safe enum (Part 1) Page 14 In prior releases, an enumerated type was the int Enum pattern: public public public public static static static static final final final final int int int int SEASON_WINTER SEASON_SPRING SEASON_SUMMER SEASON_FALL = = 0; = 1; = 2; 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  15. 15. Type-safe enum (Part 2) Page 15 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  16. 16. Type-safe enum (Part 3) Page 16 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. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  17. 17. Static Imports Page 17 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); Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  18. 18. More Features & Enhancements (1) Page 18 Concurrency: Scanner: The new concurrent package in J2SE The Scanner class uses the regex 5.0 is dedicated to creating and package to parse text input and to managing concurrent threads. This package provides utilities that will save convert that input into primitive you time and trouble creating concurrent types. applications. Scanner scan = new Scanner(System.in); The Concurrency Utilities packages System.out.print("What is your name? "); provide a powerful, extensible String name = scan.next(); framework of high-performance System.out.print("How old are you? "); threading utilities such as thread pools int age = scan.nextInt(); and blocking queues. This package String msgPattern = "Hi {0}. You are {1} frees the programmer from the need to years old."; craft these utilities by hand, in much the String msg = MessageFormat.format(msgPattern, same manner the Collections name, age); Framework did for data structures.  Additionally, these packages provide low-level primitives for advanced concurrent programming. Tiger: Java 5 Evolutions / 2006-10-25 System.out.println(msg); All rights reserved © 2005, Alcatel
  19. 19. More Features & Enhancements (2) Page 19 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. 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 public static String format( general purpose annotation (also known String pattern, as metadata) facility that permits you to Object... arguments); define and use your own annotation types. The facility consists of a syntax for The three periods after the final declaring annotation types, a syntax for parameter's type indicate that the final argument may be passed as an array or annotating declarations, APIs for reading annotations, a class file as a sequence of arguments. Varargs representation for annotations, and an can be used only in the final argument annotation processing tool. position. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  20. 20. Where to Get More Information (1) Page 20  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/whatsnew1.5.0.html. Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  21. 21. Where to Get More Information (2) Page 21  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/; Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  22. 22. Answer to Life, the Universe and Everything Page 22 Any Question? Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel
  23. 23. Page 23 www.alcatel.com Tiger: Java 5 Evolutions / 2006-10-25 All rights reserved © 2005, Alcatel

×