Java 5 Features
Java 5 Features
Venkat Subramaniam
[email protected]
http://www.agiledeveloper.com/download.aspx
Java 5 Features - 1
Abstract
Abstract A number of new features have been introduced in Java. What benefit do these
features offer you. Are there issues with using these features. For instance, when
should you use annotation? The objective of this presentation is not simply to
introduce you to the features, but to the effective use of these as well.
We will take a close look at a number of features that you will be expected to know
well when you program using Java 5.
Java 5 Features - 2
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 3
New Features
• Java 5 has introduced several new
language and API features
• One is a disaster
Java 5 Features - 4
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 5
Citizens of Java
• Java has two classes of citizens
– Objects and primitives
• You couldn’t mix them together
• What if you want to write a generalized
API to receive different types?
– Like Invoke method or even collection classes
• You had to wrap the primitive into an
object
– Predefined objects like Integer (for int),
Double (for double), etc.
• You have to wrap on send and cast on
receive
Java 5 Features - 6
Dealing with differences
• Leads to code clutter
Java 5 Features - 7
Java 5 Features - 8
+/-
• Realize that the conversion is happening
still under the hood
– Has performance consequences
• What if Integer reference is null and you
try to assign it to int
– NullPointerException
• What does == mean now?
– On Integer it is identity comparison and on
int it is value based comparison, use caution
when you mix
• Use it where performance is not critical
Java 5 Features - 9
Java 5 Features
• New Features
• Autoboxing
• for-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 10
Looping
• How can you loop?
– It depends on what you are looping over
• You can use the good old method:
for(int index = 0; index < arr.length;
index++) {…}
• Or you may use:
for(
Iterator iter = c.iterator();
iter.hasNext(); ) {… iter.next()…}
• Again, we have lived with this clutter
• How about something simpler?
Java 5 Features - 11
for-each
• How about reading it as
for each element X in collection col …
• Syntactically this may look like
foreach(X element in col) // WRONG
• But this would lead to two problems
– Would introduce two new keywords
– May step on the toe of some legacy code
• Smartly avoided with an uglier syntax ☺
for(X element : col) { …
// Each pass through loop, element refers to
// an element in the collection col
}
Java 5 Features - 12
+/-
• It does look simpler, elegant
• But you can’t use all the time
• You can’t use it if you need access to the
iterator or index it hides
– like to remove an element or set a value in a
collection using an index
• For you to use for-each, the collection
must implement a Iterable interface
– This has one method iterator() that returns
the iterator
Java 5 Features - 13
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 14
What it was?
• Type whose legal value is from fixed set of
constants
• ‘C’ enum was omitted from Java
• You want to define a select set of possible
values
• You wrote
public static final int COFFEESIZE_SMALL = 1;
public static final int COFFEESIZE_MEDIUM = 2;
public static final int COFFEESIZE_LARGE = 3;
Java 5 Features - 15
What’s wrong?
• Item #21 “Replace enum constructs with
classes” in Effective Java
– Not typesafe
– No namespace (how can you have two
enumerations within same scope?)
– Brittle – errors result from adding new ones,
may conflict with existing ones
– Not printable – how to nicely print a value of
enum?
Java 5 Features - 16
typesafe enum pattern
• Joshua’s recommendation:
Java 5 Features - 17
Advantages
• No way for you to create objects of this class
– You only have objects you have exported
• You can’t extend this class since the constructor is
private
• Provide compile-time type safety
– Except you may pass a null
• Provides namespace for defining multiple enums with
names across enums
– Like Small CoffeeSize and Small ShirtSize
• You can add constants without breaking client code
• Printable as you desire by overriding toString()
• Can add methods
• You can add the enumerations to a collection if you
want to get a list of all values
Java 5 Features - 18
Minor Disadvantages
• Hard to aggregate like Small | Large
• Can’t use switch on them – you need to
resort to if/else statements
• You are loading classes at runtime – may
be an issue for resource constrained
devices
• Pretty minor concerns, so why not use it?
Enum
• Looks like C/C++ support - only better
enum CoffeeSize { SMALL, MEDIUM,
LARGE; }
• Behind the scene enum type generation
• They are comparable and serializable
• Has values() method that returns array of
all values of enum type in order of
declaration
• Can use switch if you like
Java 5 Features - 20
Enhancing enum
• You may add data and behavior to an enum
Java 5 Features - 21
Java 5 Features - 22
+/-
• enum are very powerful
• Provide type safety
Java 5 Features - 23
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 24
Sending variable number of args
• Two reasons you forced you to send an
array to a method
Java 5 Features - 25
varargs
• varargs is a sugar coating that hides the
creation of array for you
Java 5 Features - 26
Nice work
• Ellipsis in C++ is horrible
– Hard to use
– Leads to significant issues with determining
the type correctly
• Java’s implementation is a lot more
civilized
• You may mix varargs with autoboxing as
well
• Reflection API methods like invoke accept
varargs
• System.out.printf
Java 5 Features - 27
+/-
• Use it when it makes sense to provide
flexibility of receiving variable number of
arguments
• You loose some compile time type safety
• If you are debating between say 3 and 4
parameters, you may consider
overloading instead
• If you are using varargs, then don’t
overload – leads to confusion
Java 5 Features - 28
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 29
Metadata
• You want to communicate certain intent in your
code
– Like serializable, Cloneable, etc.
Java 5 Features - 31
Java 5 Features - 33
Meta-Annotation
• You want to say a few things about the
annotation itself
– Where it can be used, how, etc.
Java 5 Features - 34
Fetching Annotation Info
• Reflection API can be used to explore the
Annotation details at runtime
programmatically
• isAnnotationPresent()
Java 5 Features - 35
apt
• Annotation Processing Tool
Java 5 Features - 36
+/-
• Annotation very powerful
• Better than using tagging interfaces
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 38
How do we use static methods?
• To use static methods, we prefix the call
with class name
– Runtime.getRuntime()
Java 5 Features - 41
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 42
Generics
• Remember the good old Templates in
C++?
• Java went the route of using Object as
generic type
– Problem is when you pull some thing out of a
collection, how do you call methods on it?
– Only after casting it to the correct type right
– Much worst if you are dealing with primitive
types
• These have to be boxed and unboxed
• Having collections that are type safe will
eliminate this issue
– Back to what C++ originally provided ☺
Java 5 Features - 43
Need?!
• This is highly debatable
• First question is do we really need a type
safe language
– What about dynamically typed languages
• If we used dynamically typed languages,
then we do not really care about
generics!
• But then, we are talking about Java here
• So, how do we solve the issues with such
a strongly typed language
Java 5 Features - 44
+/-
• Easier to write
• Intended to provide type safety
• Nice features like extends and super to control
the type for parametrized type
• No change to JVM or byte code for generics
• Good news – compatible with legacy code
• Bad news – you loose type safety
• More about generics in
– Good, Bad, and Ugly of Java Generics talk
– Three part article at
http://www.agiledeveloper.com/download.aspx
Java 5 Features - 45
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 46
Other Features
• StringBuilder
– StringBuffer eliminates object creation overhead, but has
synchronization overhead
– StringBuilder removes that overhead
• Client vs. Server side differences in garbage collection,
more adaptive collection
• Improved Image I/O for performance and memory
usage
• Reduced application startup time and footprint using
shared archive
• Enhancement to Thread Priority
• Ability to get stack trace for a thread or all threads
• UncoughtExceptionHandler on a Thread
• Improved error reporting on fatal exceptions
• System.nanoTime() for nanoseconds granularity for
time measurements
Java 5 Features - 47
Other Features…
• ProcessBuilder
– Easier than Runtime.exec() to start process
• Formatter and Formattable provide ability to
format output in printf like style
• Scanner for easier conversion to primitive types
– based on regex
• java.lang.instrument allows byte code
enhancement at runtime to instrument code
• Collections Framework has Queue,
BlockingQueue, and ConcurrentMap interfaces
and implementations. Some classes modified to
implements new interfaces
• Reflection API supports annotation, enum.
Class has been generified
• System.getenv() undeprecated!
Java 5 Features - 48
Quiz Time
Java 5 Features - 49
Java 5 Features
• New Features
• Autoboxing
• For-each
• enum
• Varargs
• Annotation
• Static Import
• Generics
• Other features
• Conclusion
Java 5 Features - 50
Love-hate of features
• Autoboxing ☺
• For-each ☺
• enum ☺
• Varargs ☺
• Annotation ☺
• Static Import
• Generics ….
Java 5 Features - 51
References
1. http://java.sun.com