New Features of Java 5.0 - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

New Features of Java 5.0

Description:

– PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 28
Provided by: cdj3
Category:
Tags: features | java | new

less

Transcript and Presenter's Notes

Title: New Features of Java 5.0


1
New Features of Java 5.0
Capital District Java Developers Network 12
October, 2005 Rod Sprattling Solentas, LLC
2
Note To 12 October Attendees
I did my promised homework before sending this
presentation off to Anthony. Select Notes View in
PowerPoint or OpenOffice Presentation to read the
comments and clarifications. Rod Sprattling 12
October 2005
3
The Big Stuff
  • Generics
  • Enumerations
  • New concurrency constructs
  • New interfaces
  • Autoboxing
  • New loop for/in

4
Less Big Stuff
  • Static imports
  • varargs
  • System.lang.Formatter
  • Annotations
  • JVM monitoring and control

5
Generics
  • Java Generics were strongly driven by desire for
    less fiddly Collections programming.
  • Like C templates, provide compile-time
    resolution of datatype abstractions that preserve
    type safety and eliminate need for casting.
  • Can employ generics in classes, interfaces and
    methods.
  • Unlike C templates, Generics are more than a
    clever macro processor Java compiler keeps track
    of generics internally, and uses same class file
    for all instances.

6
Generic Collections
  • Six core collections interfaces are
    synchronization wrappers
  • Collection abstract generic class
  • List
  • Set, SortedSet
  • Map, SortedMap
  • Non-generic collections classes (HashMap, etc.)
    still available, of course.

7
Simplify Collections Use
  • Java 1.4

LinkedList list new LinkedList() list.add(new
Integer(1)) Integer num (Integer) list.get(0)
  • Java 5

LinkedList list new LinkedList
() list.add(new Integer(1)) Integer num
list.get(0)
8
Simplify Collections Use
  • Original

HashMap celebrityCrashers new
HashMap() celebrityCrashers.put( new Date(
10/05/2005 ), new String( Lindsay
Lohan ) ) Date key new Date( "10/1/2005"
) if ( celebrityCrashers.containsKey( key ) )
System.out.println( "On " key ,
(String) celebrityCrashers.get( key )
crashed a vehicle.")
  • Extra Crispy

Map celebrityCrashers new
HashMap() celebrityCrashers.put(
new Date(10/05/2005), new String(
Lindsay Lohan ) ) Date key new
Date("10/05/2005") if ( celebrityCrashers.contain
sKey( key ) ) System.out.printf( "On tc, d
crashed a vehiclen key,
celebrityCrashers.get( key ) )
9
Defining Generics
  • Classes

class LinkedList implements List //
implementation
  • Interfaces

interface List void add(E x)
Iterator iterator()
  • Methods

void printCollection(Collection c)
for(Object oc) System.out.println(o)

10
Wildcards
  • ? extends Type a family of Type subtypes
  • ? super Type a family of Type supertypes
  • ? - the set of all Types, or any

public static
void sort(List list) Object a
list.toArray() Arrays.sort(a)
ListIterator i list.listIterator()
for(int j0 j i.set((T)aj)
11
Enumerations
  • In Java 1.4 we use Bloch's 'type safe enum'
    design pattern

// This class implements Serializable to preserve
valid equality // tests using after
deserialization. public final class PowerState
implements java.io.Serializeable private
transient final String fName private static
int fNextOrdinal 1 private final int
fOrdinal fNextOrdinal private
PowerState(String name) this.fName name
public static final PowerState ON new
PowerState("ON") public static final
PowerState OFF new PowerState("OFF") public
String toString() return fName
private static final PowerState fValues ON,
OFF private Object readResolve () throws
java.io.ObjectStreamException return
fValuesfOrdinal
12
Enumerations
  • A bit more concise in Java 5

public enum PowerState ON, OFF
  • Enum classes
  • declare methods values(), valueOf(String)
  • implement Comparable, Serializeable
  • override toString(), equals(), hashCode(),
    compareTo()

13
java.util.concurrent
  • New package that supports concurrent programming
  • Executor interface executes a Runnable
  • ThreadPoolExecutor class allows creation of
    single, fixed and cached thread pools
  • Executor also executes Callable objects. Unlike
    Runnable, Callable returns a result and can throw
    exceptions

14
New Ability Interfaces
  • Iterable advertises the class implements
    Interator with hasNext(), next() methods.
    Introduced to make for/in loop work.
  • Appendable implemented by classes that can have
    a char or CharSequence appended to it (e.g.,
    StringBuffer, CharBuffer)
  • Readable implemented by classes that can
    sequentially copy chracters into a buffer.

15
New Ability Interfaces
  • Closeable, Flushable implemented by classes
    that provide close() and flush() methods
  • Formattable implemented by classes that want to
    have finer control over text formatting, using
    the java.util.Formatter class, than toString()
    can give. Formatter underlays printf() and
    format()..

16
Autoboxing
  • Easier conversion between primative and reference
    types

// Java 1.4 List numbers new
ArrayList() numbers.add(new Integer(-1)) int i
((Integer)numbers.get(0)).intValue() // Java
5 List numbers new ArrayList() numbers.add(-1)
// Box int to Integer int i
numbers.get(0) // Unbox Integer to int
17
Static Imports
  • Langauge support makes it easier to import static
    members from another class. No more BigBagOf
    Constants interfaces.

import static com.solentas.Agent.RunState.NEW imp
ort static com.solentas.Agent.RunState.READY impo
rt static com.solentas.Agent.RunState.RUNNING imp
ort static com.solentas.Agent.RunState.BLOCKED im
port static com.solentas.Agent.RunState.TERMINATED
// import static com.solentas.Agent.RunState.
//.... agent.state RUNNING
18
Enhanced for Loop
Collection temperatures new
LinkedHashSet() temperatures.add(105)
temperatures.add(92) temperatures.add(7) for(In
teger aTemp temperatures)
System.out.println("This temperature is "
aTemp)
  • Hides the loop counter or Iterator....
  • ...but therefore can't be used when your code
    needs the counter or Iterator.

19
Variable Argument List
  • varargs mechanism allows variable length argument
    lists. Used in System.out.printf(), format()
    method of String and java.util.Formatter

public static int min(int first, int...
rest) int min first for(int next rest)
if (next Note the last argument is typed. // C varargs are
untyped (unsafe!) // int min(int first,
...) // Cyclone C lets you type (safer!) //
int min(int first, ...int_t args)
20
java.util.Formatter Class
  • Provides control of string formatting akin to C's
    printf()
  • Utilizes a format string and format specifiers
  • Unlike C format strings, note use of as sole
    format specifier. No backslashes, such as \n

System.out.printf(s crashed on tcn,
celebName, crashDate)
21
Annotations
  • Let you associate metadata with program elements
  • Annotation name/value pairs accessible through
    Reflection API
  • Greatest utility is to tools, such as code
    analyzers and IDEs. JDK includes apt tool that
    provides framework for annotation processing
    tools.

22
Annotations
  • Most useful annotation to programmer_at_Override

interface Driver //... int
getDrivingSkillsIndex() public class
Celebrity implements Driver //... /
The _at_Override annotation will let the compiler
catch the misspelled getDrivinSkillsIndex().
/ _at_Override getDrivinSkillsIndex() return 0
//...
23
Annotations
  • Next most useful annotations to
    programmers_at_Deprecated, _at_SuppressWarnings

_at_Deprecated public class BuggyWhip ...
//... // _at_SuppressWarnings selectively turns
off javac warnings // raised by use of the -Xlint
option _at_SuppressWarnings(fallthrough) public
void iUseSloppySwitchCoding ...
24
Annotations
  • You can define your own (e.g., to supplant
    javadoc tags, or annotate for code management
    practices)
  • See Chapter 4 of Java In A Nutshell

25
Monitoring Management
  • JMX API (javax.management) provides remote
    monitoring and management of applications
  • java.lang.management uses JMX to define MXBean
    interfaces for monitoring and managing a running
    JVM
  • MXBean interface lets you monitor class loadings,
    compilation times, garbage collections, memory,
    runtime configuration and thread info.
  • MXBean also provides for granting of JVM
    monitoring and control permission

26
Monitoring Management
  • java.lang.instrument defines the API to define
    agents that instrument a JVM by transforming
    class files to add profiling support, code
    coverage testing
  • Instrumentation agent classes define premain()
    method, which is called during startup before
    main() for each agent class specified on the Java
    interpreter command line
  • Instrumentation object can register
    ClassFileTransformer objects to rewrite class
    file byte codes as they're loaded.

27
References Credits
  • Sun J2SE 5 tutorial http//java.sun.com/developer/
    technicalArticles/J2SE/generics/
  • Java 5 In A Nutshell (O'Reilly's Nutshell Series)
  • A quick tour 'round Java 5http//www.clanproduc
    tions.com/java5.html
  • Type Safe Enumerationshttp//www.javapractices.
    com/Topic1.cjpLegacy
Write a Comment
User Comments (0)
About PowerShow.com