java 5 new language features l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Java 5: New Language Features PowerPoint Presentation
Download Presentation
Java 5: New Language Features

Loading in 2 Seconds...

play fullscreen
1 / 116

Java 5: New Language Features - PowerPoint PPT Presentation


  • 258 Views
  • Uploaded on

Java 5: New Language Features Eben Hewitt August 2005 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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Java 5: New Language Features' - jana


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
java 5 new language features

Java 5:New Language Features

Eben Hewitt August 2005

goal of this presentation
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
coming jdk 5 presentations
Coming JDK 5 Presentations
  • Generics
  • Annotations
  • Concurrency
  • Instrumentation
topics in this presentation
Topics in this Presentation
  • JDK 5 Overview
  • Swing Things
  • For-Each Loop
  • Static Imports
  • Autoboxing
  • Typesafe Enums
  • Var-args

//cont...

topics in this presentation cont
Topics in this Presentation cont.
  • Covariants
  • Able-Interfaces
  • Formatter
  • Scanner
  • Xpath Improvements
  • Miscellaneous Features
    • StringBuilder
    • Hexadecimal FP Literals
    • Regex Improvements
  • Reasons to Migrate
jdk 5 overview
JDK 5 Overview
  • Implements 15 new JSRs
    • See JSR 176
    • http://www.jcp.org/en/jsr/detail?id=176
  • Performance Improvements
adding components
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);

desktop enhancements
Desktop Enhancements
  • Look and feel: Ocean, Synth
  • JTable printing
  • Multilingual fonts
ocean look and feel
Ocean Look and Feel
  • Default LNF
  • It’s a private custom MetalTheme, so your custom MetalThemes won’t be affected.
synth the skinnable lnf
Synth—The 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.
synth look and feel cont
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
synth example
Synth Example

//Demo SynthExample.java

printable jtables
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).
printable jtables cont
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".

for each loop means
For-Each Loop means...
  • Don’t have to calculate loop beginning and end
  • Don’t have to get parameterized Iterator.
  • Works with Collections and Arrays
for each syntax
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

iterable interface
Iterable interface
  • For/Each loop is made possible by newjava.lang.Iterableinterface.
  • Must implement this interface if you want your class available for For/Each loop.

public interface Iterable<T>{Iterator<T> iterator();}

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

Implementing Iterable:
for each and casting
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();

for each loop advantages
For-Each Loop Advantages
  • Simpler
  • Easier to read
  • Because you don’t need to declare the iterator, you don’t have to parameterize it.
for each restrictions
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
for each recommendations
For-Each Recommendations
  • Use the for-each loop anywhere and everywhere possible.
static imports allow you to
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.
static imports recommendations
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
autoboxing31
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
autoboxing occurs
Autoboxing Occurs…
  • In method and constructor calls
  • In expressions
  • In switch/case statements
autoboxing example
Autoboxing Example

ArrayList<Integer> ints = new ArrayList<Integer>(1);

ints.add(1);

for (int i : ints) {

ints.get(0);

}

//remember--you can’t modify the list in the for loop!

slide34
Quiz
  • Is this valid?

Boolean b = FALSE;

while(b) { }

beware comparisons
Beware Comparisons

//prints TRUE in Java 5

//but is ILLEGAL in Java 1.4

System.out.println(new Integer(7) == 7);

slide36
Quiz
  • What values for i and j make this an infinite loop?

while (i <= j && j <= i && i != j){ }

autobox recommendations
Autobox Recommendations
  • Nice shortcut when meaning is clear.
  • Use primitives wherever you don’t require an object.
  • Be very careful when using in comparisons.
  • Be careful when using in conjunction with varargs feature.
enum overview
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;

What’s the problem with this?

answer
Answer
  • Nothing prevents this:

int shirtSize = 42;

enum traits
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.
  • AlsoEnumSet<E extends Enum<E>>and EnumMap<K extends Enum<K>,V>
simplest enum example
Simplest Enum Example

public enum Size {

SMALL,

MEDIUM,

LARGE,

XLARGE

}

Size shirtSize = Size.LARGE;

//DEMO: EnumDemo.java

complex enums
Complex Enums

//Demo EnumDemo2.java

enumset
EnumSet

public abstract class EnumSet <E extends Enum<E>>

extends AbstractSet<E>

implements Cloneable, Serializable

enumset45
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.
enumset declaration
EnumSet Declaration

public abstract class EnumSet <E extends Enum<E>>

extends AbstractSet<E>

implements Cloneable, Serializable

enumset demo
EnumSetDemo

//Demo EnumSetDemo.java

dte enum example
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.

enum example from the api
Enum Example from the API:
  • java.util.conncurrent.TimeUnit:MICROSECONDS, MILLISECONDS, NANOSECONDS, SECONDS
  • Example:

TimeUnit.MILLISECONDS.sleep(200);

enum advantages
Enum Advantages
  • Compile-time and runtime checks
  • Can do almost everything a class can do
  • Don’t get confused by which ints to pass in in a big hierarchy like Swing’s
enum recommendations
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.
varargs
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.

var args demo
Var-Args Demo

//Demo VarArgsDemo.java

var args behavior
Var-Args Behavior
  • Most specifically-matching method is called, considered are:
    • Number of args
    • Arg types
    • Autoboxing
dte varargs example
DTE Varargs Example

The DataKey class has this declaration:

public DataKey(String keyName, String[] alias);

Could change to:

public DataKey(String keyName, String... alias);

advantages of var args
Advantages of Var-Args
  • Simplified calls
  • Easier to read and write
  • Flexible API
disadvantages to var args
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
recommendations for var args
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.
covariants61
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
existing able interfaces
Existing - Able Interfaces

Existing -able interfaces include

  • Runnable
  • Comparable
  • Serializable
  • Cloneable
  • etc.
new able interfaces
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>
java lang iterable
java.lang.Iterable
  • Indicates that something returns an Iterator<T>
  • To accommodate new For/Each loop
java lang appendable
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

java lang readable
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.
java io closeable
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.
java io flushable
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.
java util concurrent callable v
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.

formatter overview
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
java util formatter
java.util.Formatter

Formatter format(String fmtStr, Object…args)

  • All format conversions consist of a single character.Must have same number of formatters as data args.
  • Formatters match left to right.
formatter usage
Formatter Usage
  • Formatting Strings DirectlyUse staticString.format():

Formatter f = new Formatter();

f.format("A %S's temperature is %.2f.", "Human", 98.6);

out.println(f);

  • Demo FormatterDemo.java
useful formatter constructors
Useful Formatter Constructors
  • Formatter()
  • Formatter(Appendable a)
  • Formatter(File f)
  • Formatter(OutputStream)
  • Formatter(Locale l)
  • Formatter(PrintStream ps)
  • Formatter(String s)
common format codes
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

more on formatting
More on Formatting
  • Formats include
    • To uppercase
    • Date/Time
    • Locales
    • Indexing
argument indexes
Argument Indexes

Use %$ to indicate the ordinal & value:

f.format("%3$d %1$d %2$d", 100, 200, 300);

relative indexes
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

formatter example
Formatter Example

//Demo FormatterDemo.java

slide81
Quiz

What does the following print?

out.print("H" + "i");

out.println('h' + 'i');

quiz solution
Quiz Solution
  • Result: Hi209
  • Solution:

out.printf("%c%c",'H',‘i');

scanner84
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
how scanner works
How Scanner Works
  • Reads tokens from underlying source
    • Whitespace is default delimiter
    • Call ScanneruseDelimiter(String s) or ScanneruseDelimiter(Pattern p) to set your own.
  • Tokens are read by matching regexes
  • Allows custom definitions and provides many predefined patterns
how to use scanner
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.
scanner87
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.
scanner example
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);

scanner and stringtokenizer
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.
advanced scanner demo
Advanced Scanner Demo
  • Demo DataScanner.java
xpath api
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
xpath usage
XPath Usage

XPath xpath = XPathFactory.newInstance(). newXPath();

Node resultNode = (Node) xpath.evaluate(xpathExpression, docroot, XPathConstants.NODE);

xpath usage95
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);
xpath demo
XPath Demo
  • Demo XPathDemo.java
xpath recommendations
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 isn’t javax.xml.xpath.XPathConstants an enum?
process processbuilder
Process & ProcessBuilder
  • Used to create OS processes.
  • start()method creates a new Process instance with those attributes.
  • Demo ProcessBuilderDemo.java
stringbuilder
StringBuilder
  • For large (10,000+) StringBuffer operations
  • Unsynchronized, but you can use locks/monitors
  • Roughly %10 faster than StringBuffer
  • Available in C#
stringbuilder example
StringBuilder Example
  • //Demo StringBuilderDemo.java
regex improvements
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.

java util regex matchresult
java.util.regex.MatchResult
  • Now you can calltoMatchResult()
  • //Demo RegexMatchResultDemo.java
new bit manipulation methods
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
hexadecimal floating point literals
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.
why sun added hexadecimal fp literals
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.”

hexadecimal fp literal usage
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.

hexadecimal example
Hexadecimal Example

Demo HexadecimalDemo.java

hexadecimal fp literal notes
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
reasons to migrate111
Reasons to Migrate
  • Improved performance
  • New Language Features
  • Ease of use
unicode 4 0 support
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 0x0000through 0xFFFF
performance
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/
performance class data sharing
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.
performance ergonomics
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