1 / 116

Java 5: New Language Features

Goal of this Presentation. Understand new language constructs in JDK 5Understand additions/changes to the APISee the usefulness of new features in real examplesTie concepts back to our organizationDoes not include topics in coming presentations. Coming JDK 5 Presentations. GenericsAnnotationsC

treva
Download Presentation

Java 5: New Language Features

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. Java 5: New Language Features Eben Hewitt August 2005

    2. Goal of this Presentation Understand new language constructs in JDK 5 Understand additions/changes to the API See the usefulness of new features in real examples Tie concepts back to our organization Does not include topics in coming presentations

    3. Coming JDK 5 Presentations Generics Annotations Concurrency Instrumentation

    4. Topics in this Presentation JDK 5 Overview Swing Things For-Each Loop Static Imports Autoboxing Typesafe Enums Var-args //cont...

    5. Topics in this Presentation cont. Covariants Able-Interfaces Formatter Scanner Xpath Improvements Miscellaneous Features StringBuilder Hexadecimal FP Literals Regex Improvements Reasons to Migrate

    6. JDK 5 Overview Implements 15 new JSRs See JSR 176 http://www.jcp.org/en/jsr/detail?id=176 Performance Improvements

    7. Swing Things

    8. Adding Components In JDK 1.4 to add a component to the "content pane": JComponent component; JFrame frame; //create component and frame frame.getContentPane().add(component); In JDK 5, Swing does it for you: JComponent component; JFrame frame; //create the component and frame frame.add(component);

    9. Desktop Enhancements Look and feel: Ocean, Synth JTable printing Multilingual fonts

    10. Ocean Look and Feel Default LNF Its a private custom MetalTheme, so your custom MetalThemes wont be affected.

    11. Ocean Screenshot

    12. SynthThe Skinnable LNF Enables creating a custom look without code. Allow appearance to be configured from images. Provide the ability to customize the look of a component based on its name property. Provide a centralized point for overriding the look of all components. Enable custom rendering based on images.

    13. Synth Look and Feel cont. No way to specify layout. No default look! Synth is an empty canvas. Has NO default bindings and, unless customized, paints nothing. Synth DTD: http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/plaf/synth/doc-files/synthFileFormat.html javax.swing.plaf.synth

    14. Synth Implementation Screenshot

    15. Synth Example //Demo SynthExample.java

    16. Printable JTables No-arg print() method prints the JTable with no header or footer selects FIT_WIDTH print mode (as opposed to NORMAL). Opens the print dialog (default).

    17. Printable Jtables cont... try { print(PrintMode.NORMAL, new MessageFormat( "Personal Info"), new MessageFormat("Page {0,number}")); } catch (PrinterException e) { e.printStackTrace(); } //Header will be bold faced and centered, and contain the text "Personal Info". //Footer will consist of the centered text "Page 1".

    18. For-Each Loop

    19. For-Each Loop means... Dont have to calculate loop beginning and end Dont have to get parameterized Iterator. Works with Collections and Arrays

    20. For-Each Syntax for (Product p : Cart) Read this as: For each Product object in the Collection of Products called Cart, execute the body of the loop. Call the current Product in the iteration p. //Demo DemoForEach.java

    21. Iterable interface For/Each loop is made possible by new java.lang.Iterable interface. Must implement this interface if you want your class available for For/Each loop. public interface Iterable<T>{ Iterator<T> iterator(); }

    22. Implementing Iterable: AbstractCollection AbstractList AbstractQueue AbstractSequentialList AbstractSet ArrayBlockingQueue ArrayList AttributeList BeanContextServicesSupport BeanContextSupport ConcurrentLinkedQueue CopyOnWriteArrayList CopyOnWriteArraySet DelayQueue EnumSet HashSet JobStateReasons LinkedBlockingQueue LinkedHashSet LinkedList PriorityBlockingQueue PriorityQueue RoleList RoleUnresolvedList Stack SynchronousQueue TreeSet Vector

    23. For-Each and Casting You must use Generics if you need to cast on retrieval. void cancelAll(Collection<TimerTask> c) { for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); ) i.next().cancel(); } Eliminate Iterator: void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel();

    24. For-Each Loop Advantages Simpler Easier to read Because you dont need to declare the iterator, you dont have to parameterize it.

    25. For-Each Restrictions You cannot use for-each to: Remove elements as you traverse collections (hides the Iterator) Modify the current slot in an array or list Iterate over multiple collections or arrays in parallel

    26. For-Each Recommendations Use the for-each loop anywhere and everywhere possible.

    27. Static Imports

    28. Static Imports allow you to... Import static members one at a time: import static java.lang.Math.PI; or everything in a class: import static java.lang.Math.*; Note you must fully qualify imports. The compiler will indicate ambiguities.

    29. Static Imports Recommendations Use it when you: Require frequent access to static members from one or two classes Overuse can make your program unreadable and unmaintainable. Import members individually by name, not using *. Organize static imports above regular imports in class definition

    30. Autoboxing

    31. Autoboxing Automatically converts a primitive type to its corresponding wrapper when an object is required. Automatically converts a wrapper to its corresponding primitive when a primitive is required. Once values are unboxed, standard conversions apply

    32. Autoboxing Occurs In method and constructor calls In expressions In switch/case statements

    33. Autoboxing Example ArrayList<Integer> ints = new ArrayList<Integer>(1); ints.add(1); for (int i : ints) { ints.get(0); } //remember--you cant modify the list in the for loop!

    34. Quiz Is this valid? Boolean b = FALSE; while(b) { }

    35. Beware Comparisons //prints TRUE in Java 5 //but is ILLEGAL in Java 1.4 System.out.println( new Integer(7) == 7);

    36. Quiz What values for i and j make this an infinite loop? while (i <= j && j <= i && i != j){ }

    37. Autobox Recommendations Nice shortcut when meaning is clear. Use primitives wherever you dont require an object. Be very careful when using in comparisons. Be careful when using in conjunction with varargs feature.

    38. Typesafe Enums

    39. Enum Overview C/C++ has had first-class enums for years. Java developers had to do this: static final int SMALL = 0; static final int MEDIUM = 1; static final int LARGE = 2; Whats the problem with this?

    40. Answer Nothing prevents this: int shirtSize = 42;

    41. Enum Traits Can be declared in a class but not in a method. Can have constructors and methods. Cannot directly instantiate an enum. Values must be very first declaration. Also EnumSet<E extends Enum<E>> and EnumMap<K extends Enum<K>,V>

    42. Simplest Enum Example public enum Size { SMALL, MEDIUM, LARGE, XLARGE } Size shirtSize = Size.LARGE; //DEMO: EnumDemo.java

    43. Complex Enums //Demo EnumDemo2.java

    44. EnumSet public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

    45. EnumSet Set implementation for use with Enums All elements must come from a single enum. Internally represented as bit vectors for speed. Not synchronized The Iterator returned: traverses elements in declared ordered is weakly consistent.

    46. EnumSet Declaration public abstract class EnumSet <E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

    47. EnumSet Demo //Demo EnumSetDemo.java

    48. DTE Enum Example We could use enums in DateTimeUtils class to represent the different allowable formats: public static Date stringToDate(String input, int format) switch (format) { case YYYY_MM_DD_DATE_FORMAT: case MM_SLASH_DD_SLASH_YYYY_DATE_FORMAT: //etc.

    49. Enum Example from the API: java.util.conncurrent.TimeUnit: MICROSECONDS, MILLISECONDS, NANOSECONDS, SECONDS Example: TimeUnit.MILLISECONDS.sleep(200);

    50. Enum Advantages Compile-time and runtime checks Can do almost everything a class can do Dont get confused by which ints to pass in in a big hierarchy like Swings

    51. Enum Recommendations Use methods generally to add descriptive information to fields. Keep them simple. Do not overuse fields, methods, and constructors. EnumSet and EnumMap should be rarely used.

    52. Variable Length Argument Lists

    53. Varargs Alternate syntax for providing a variable number of arguments to a method. Used to have to use Object[] Instead of public static void main(String[] args) Write: public static void main(String... args) Simply write your arguments without creating an array.

    54. Var-Args Demo //Demo VarArgsDemo.java

    55. Var-Args Behavior Most specifically-matching method is called, considered are: Number of args Arg types Autoboxing

    56. DTE Varargs Example The DataKey class has this declaration: public DataKey(String keyName, String[] alias); Could change to: public DataKey(String keyName, String... alias);

    57. Advantages of Var-Args Simplified calls Easier to read and write Flexible API

    58. Disadvantages to Var-Args Can cause confusion and RuntimeExceptions overloaded constructors could let you compile with wrong arguments, but get ArrayIndexOutOfBoundsException Can cause confusion in knowing which method was intended

    59. Recommendations for Var-Args Hesitate to create new APIs with var-args If you do, do not use var-args on overloaded methods. Beware autoboxing. Document the purpose of vararg-ing.

    60. Covariants

    61. Covariants Allows creation of methods in a subclass that return an object whose type is a subtype of that returned by the method it overrides. Used to get this message: someMethod() in Sub cannot override someMethod() in Super; attempting to use incompatible return type. //Demo DemoCovariants.java

    62. Able Interfaces

    63. Existing - Able Interfaces Existing -able interfaces include Runnable Comparable Serializable Cloneable etc.

    64. New -Able Interfaces java.lang.Iterable java.lang.Appendable java.lang.Readable java.io.Closeable java.io.Flushable java.util.Formattable java.util.concurrent.Callable<V>

    65. java.lang.Iterable Indicates that something returns an Iterator<T> To accommodate new For/Each loop

    66. java.lang.Appendable An Appendable object is one that can have a character or CharSequence (or a sub-sequence of a CharSequence ) appended to it. Implementations include StringBuffer and StringBuilder, Writer (and subclasses), PrintStream, and java.nio.CharBuffer. Appendable was created for the benefit of java.util.Formatter

    67. java.lang.Readable The java.lang.Readable interface is the opposite of Appendable: a Readable object can transfer characters into a supplied CharBuffer. java.io.Reader and all of its subclasses are Readable (of course), and so is CharBuffer itself. Readable was created for the benefit of java.util.Scanner.

    68. java.io.Closeable Intended to be implemented by any classes that have a close()method, such as FileOutputStream. Note that many other apparently closeable things do NOT implement Closeable (such as Socket, Connection, Statement). The NIO ServerSocketChannel, SelectableChannel, Pipe.SinkChannel and others in NIO DO, however, implement it.

    69. java.io.Flushable Intended to be implemented by any classes that have a flush() method, such as FileOutputStream. Flushable is implemented by output stream classes and Formatter.

    70. java.util.concurrent. Callable<V> Similar to Runnable except: 1. It indicates a task that returns a result (Future<T>) 2. The task may throw a checked exception.

    71. Formatter

    72. Formatter Overview public final class Formatter implements Closeable, Flushable interpreter for C's printf-style format strings Supports: Common formats for numeric, string, and date/time data, and locale-specific output. Layout justification and alignment Arbitrary types via Formattable

    73. java.util.Formatter Formatter format(String fmtStr, Objectargs) All format conversions consist of a single character. Must have same number of formatters as data args. Formatters match left to right.

    74. Formatter Usage Formatting Strings Directly Use static String.format(): Formatter f = new Formatter(); f.format("A %S's temperature is %.2f.", "Human", 98.6); out.println(f); Demo FormatterDemo.java

    75. Useful Formatter Constructors Formatter() Formatter(Appendable a) Formatter(File f) Formatter(OutputStream) Formatter(Locale l) Formatter(PrintStream ps) Formatter(String s)

    76. Common Format Codes c = Unicode character s = String d = decimal f = floating point n = line.separator t = prefix for date and time characters //specify //see java.util.Formatter Javadoc for many more

    77. More on Formatting Formats include To uppercase Date/Time Locales Indexing

    78. Argument Indexes Use %$ to indicate the ordinal & value: f.format("%3$d %1$d %2$d", 100, 200, 300);

    79. Relative Indexes Allow you to reuse the same argument Use %<s Formatter f = new Formatter(); f.format("%3$d %1$d %2$d", 100, 200, 300); Demo FormatterDemo.java

    80. Formatter Example //Demo FormatterDemo.java

    81. Quiz What does the following print? out.print("H" + "i"); out.println('h' + 'i');

    82. Quiz Solution Result: Hi209 Solution: out.printf("%c%c",'H',i');

    83. Scanner

    84. Scanner Complement to Formatter Reads formatted input and converts it into binary form. Reads input from any Readable or ReadableByteChannel The Console A File String

    85. How Scanner Works Reads tokens from underlying source Whitespace is default delimiter Call Scanner useDelimiter(String s) or Scanner useDelimiter(Pattern p) to set your own. Tokens are read by matching regexes Allows custom definitions and provides many predefined patterns

    86. How to Use Scanner Determine if an input is available by calling a hasNextX() method. Read available input using nextX(); Repeat to end of input.

    87. Scanner Easy to get text into a non-GUI application (System.in) Uses the regex package to parse text input and to convert that input into primitive types.

    88. Scanner Example Retrieve a string and an integer from the console: 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);

    89. Scanning Data

    90. Scanner and StringTokenizer StringTokenizer is not deprecated, but is discouraged for new code. Instead use the split method of String or the java.util.regex package.

    91. Advanced Scanner Demo Demo DataScanner.java

    92. XPath

    93. XPath API XPath provides access to the XPath evaluation environment and expressions. Static XPathFactory newInstance() Returns an XPath instance for creating XPath objects XPath newXPath() Returns an XPath object for evaluating XPath expressions String evaluate(String expression, Object start) Evaluates an expression from start (Node or NodeList) forward. Object evaluate(String expression, Object start, QName resultType) ResultType is one of the XPathConstants STRING, NODE, NODESET, NUMBER, or BOOLEAN

    94. XPath Usage XPath xpath = XPathFactory.newInstance(). newXPath(); Node resultNode = (Node) xpath.evaluate( xpathExpression, docroot, XPathConstants.NODE);

    95. XPath Usage XPath expressions can be compiled into an internal format and reused. String x = "/node"; XPathExpression xpath = xpathprocessor.compile(x); ... NodeList nodes = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);

    96. XPath Demo Demo XPathDemo.java

    97. XPath Recommendations Instead of using two (or more) separate methods for getting a single node or multiple nodes, you pass in a XPathConstants value to specify what you want. Start using the new XPath constructs everywhere possible. Don't use a series of XPath expression queries for large amounts of data where performance is an issue. Use SAX instead. Why isnt javax.xml.xpath.XPathConstants an enum?

    98. Miscellaneous Features

    99. Process & ProcessBuilder Used to create OS processes. start() method creates a new Process instance with those attributes. Demo ProcessBuilderDemo.java

    100. StringBuilder For large (10,000+) StringBuffer operations Unsynchronized, but you can use locks/monitors Roughly %10 faster than StringBuffer Available in C#

    101. StringBuilder Example //Demo StringBuilderDemo.java

    102. RegEx Improvements When using a non-trivial Pattern, each call to the find() method of a Matcher can generate a lot of state: start position end position text of the match start, end, and text of each sub-expression of the Pattern. Before Java 5.0, you had to get this state from the Matcher by following each call to find() with various calls to start(), end(), and group(), as needed.

    103. java.util.regex.MatchResult Now you can call toMatchResult() //Demo RegexMatchResultDemo.java

    104. New Bit Manipulation Methods Seven methods added to Integer and Long. Include: int bitCount int highestOneBit int lowestOneBit int numberOfLeadingZeros int numberOfTrailingZeros int reverse int rotateLeft int rotateRight

    105. Hexadecimal Floating Point Literals A floating-point literal in hexadecimal notation begins with 0X or 0x. This is followed by hexadecimal digits that form the significand of the number. These digits may include a decimal point.

    106. Why Sun Added Hexadecimal FP Literals To allow precise and predictable specification of particular floating-point values, hexadecimal notation can be used for floating-point literals and for string- to-floating-point conversion methods in Float and Double.

    107. Hexadecimal FP Literal Usage Required: After the significand comes the exponent. Instead of using e or E to introduce the exponent, hexadecimal floating-point literals use p or P. The p or P is followed by the exponent (as in "power of"), which must be a decimal number, not a hexadecimal number. This is a binary exponent, not a decimal exponent. That is, it represents the power of two to which the significand should be raised.) The value can be followed by an f or F to indicate a float literal, or a d or D to indicate a double literal.

    108. Hexadecimal Example Demo HexadecimalDemo.java

    109. Hexadecimal FP Literal Notes If you really need to know exactly what bits are being set in a float or double value, then you really want a hexadecimal literal. Notice that Float.MAX_VALUE now indicates that the largest float value is 0x1.fffffeP+127f

    110. Reasons to Migrate

    111. Reasons to Migrate Improved performance New Language Features Ease of use

    112. Unicode 4.0 Support Support for Unicode 4 (code points) Character and String have new methods to manipulate supplementary characters Characters beyond the base range of 0x0000 through 0xFFFF

    113. Performance Up to 275% faster. Enhancements to program execution speed include: Garbage collection ergonomics StringBuilder class Java 2D technology enhancements Performance and memory usage improvements to image I/O. Portal: http://java.sun.com/performance/

    114. Performance: Class Data Sharing Aimed at reducing application startup time and footprint. Installation process loads a set of classes from the system jar file into a private, internal representation, then dumps that representation to a "shared archive" file. During subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the JVM's metadata for these classes to be shared among multiple JVM processes.

    115. Performance Ergonomics Default selection for the garbage collector, heap size, and runtime compiler are now chosen automatically. New heap tuning allows the user to specify performance and memory utilization criteria to dynamically tune the sizes of the heap. Low-Pause Garbage Collection due to Concurrency

    116. Discussion

More Related