java 5 new language features l.
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

  • 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

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
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.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


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


In JDK 5, Swing does it for you:

JComponent component;

JFrame frame;

//create the component and frame


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:
  • javax.swing.plaf.synth
synth example
Synth Example


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



//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”.


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




























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(); );


Eliminate Iterator:

void cancelAll(Collection<TimerTask> c) {

for (TimerTask t : c)


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
  • 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);


for (int i : ints) {



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

  • 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);

  • 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?

  • 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 {






Size shirtSize = Size.LARGE;


complex enums
Complex Enums



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

extends AbstractSet<E>

implements Cloneable, Serializable

  • 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


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



enum example from the api
Enum Example from the API:
  • Example:


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.
  • 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


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.
  • 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
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.util.Formattable
  • java.util.concurrent.Callable<V>
java lang iterable
  • Indicates that something returns an Iterator<T>
  • To accommodate new For/Each loop
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
  • The java.lang.Readable interface is the opposite of Appendable: a Readable object can transfer characters into a supplied CharBuffer.
  • 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
  • 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
  • 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

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

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


  • Demo
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


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


formatter example
Formatter Example



What does the following print?

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

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

quiz solution
Quiz Solution
  • Result: Hi209
  • Solution:


  • 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.
  • Easy to get text into a non-GUI application (
  • 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.out.print("What is your name? ");

String name =;

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


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
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
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
  • 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
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
  • Now you can calltoMatchResult()
  • //Demo
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


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
  • 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:
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