java 1.5 features
DESCRIPTION
Introduction to JDK 1.5 and its features Formatted I/O Enhanced for loop Static Imports Enumeration Types Autoboxing / Unboxing StringBuilderTRANSCRIPT
Java 1.5 Features
Mohan Bang
Presentation Agenda
Enhanced for loop3
Enumeration Types5
Formatted I/O32
Static Imports34
Introduction to JDK 1.5 and its features1
Presentation Agenda
Autoboxing / Unboxing6
Complementary Features8
Questions10
Improvement / Performance37
Final Comments39
§1. Introduction to JDK 1.5 and its features
Version Code Name Release Date
JDK 1.0JDK 1.1JDK 1.1.4JDK 1.1.5JDK 1.1.6JDK 1.1.7JDK 1.1.8J2SE 1.2J2SE 1.2.1J2SE 1.2.2J2SE 1.3J2SE 1.3.1J2SE 1.4.0J2SE 1.4.1J2SE 1.4.2J2SE 5.0 (1.5.0)J2SE 6.0 (1.6.0)J2SE 7.0 (1.7.0)
Oak(none)SparklerPumpkinAbigailBrutusChelseaPlayground(none)CricketKestrelLadybirdMerlinHopperMantisTigerMustangDolphin
Jan 23, 1996Feb 19, 1997Sept 12, 1997Dec 3, 1997April 24, 1998Sept 28, 1998April 8, 1999Dec 8, 1998March 30, 1999July 8, 1999May 8, 2000May 17, 2001Feb 6, 2002Sept 16, 2002June 26, 2003Sept 30, 2004Dec 11, 2006Not Yet Released
Java History
The main difference between Java 5 and Java 6 is performance. In Java 6 performance is good as compare to Java 5.
The Java 7 Dolphin Project began in August 2006 and is tentatively scheduled for release in late 2010. The development period is organized into ten milestones; as of April 2010, milestone 7 is in progress.
The Windows JRE download has not grown significantly in recent memory
Java 1.4.2 Java 5 (1.5) Java 6 (1.6)JRE 15.10 MB 16.13 MB 15.42 MB SDK 49.33 MB 51.82 MB 72.90 MB
Java Release
Initial Release
Java Evolution
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Oak Designed for embedded devices
Java Evolution
Major additions included:• an extensive retooling of the AWT event model
• inner classes added to the language
• JavaBeans
• JDBC
• RMI
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java Evolution
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Major additions included:• strictfp keyword
• reflection which supports Introspection only, no modification at runtime possible.
• the Swing graphical API was integrated into the core classes
• Sun's JVM was equipped with a JIT compiler for the first time
• Java Plug-in
• Java IDL, an IDL implementation for CORBA interoperability
• Collections framework
Java Evolution
Major additions included:• HotSpot JVM included
• RMI was modified to support optional compatibility with CORBA
• JavaSound
• Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension)
• Java Platform Debugger Architecture (JPDA)
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java Evolution
Major additions included:• assert keyword
• regular expressions modeled after Perl regular expressions
• exception chaining allows an exception to encapsulate original lower-level exception
• Internet Protocol version 6 (IPv6) support
• non-blocking NIO (New Input/Output)
• logging API
• image I/O API for reading and writing images in formats like JPEG and PNG
• integrated XML parser and XSLT processor (JAXP)
• integrated security and cryptography extensions (JCE, JSSE, JAAS)
• Java Web Start included
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java Evolution
Major additions included:• Generics
• Metadata:
• Autoboxing/unboxing
• Enumerations
• Swing: New skinnable look and feel, called synth.
• Varargs
• Enhanced 'for loop'
• Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory.
• Automatic stub generation for RMI objects.
• static imports
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java Evolution
Major additions included:•Support for older Win9x versions dropped.
•Scripting Language Support (JSR 223)
•Dramatic performance improvements for the core platform[15][16], and Swing.
•Improved Web Service support through JAX-WS (JSR 224)
•JDBC 4.0 support (JSR 221).
•Java Compiler API (JSR 199)
•Upgrade of JAXB to version 2.0
•Support for pluggable annotations (JSR 269).
•Many GUI improvements
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
Java Evolution
Major additions included:• JVM support for dynamic languages, following the prototyping work currently done on the Multi Language Virtual Machine,
• A new library for parallel computing on Multi-core processors[26],
• Superpackages (JSR 294), which are a way to define explicitly in a library or module which classes will be visible from outside of the library[27],
• Swing Application Framework, an infrastructure common to most desktop applications, making Swing applications easier to create.
• Replacing the existing concurrent low-pause garbage collector
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE 6
Java SE 7
java.applet, java.awt, java.io, java.lang, java.net, java.util
java.math, java.rmi, java.security, java.sql, java.text, java.beans
javax.accessibility, javax.swing, org.omg
javax.naming, javax.sound, javax.transaction
java.nio, javax.imageio,javax.net, javax.print,javax.security, org.w3c
javax.activity,javax.management
Java 1.08 packages212 classes
Java 1.123 packages504 classes
Java 1.259 packages1520 classes
Java 1.377 packages1595 classes
Java 1.4103 packages2175 classes
Java 1.5131 packages2656 classes
New Events
Inner class
Object Serialization
Jar Files
International
Reflection
JDBC
RMI
JFC/Swing
Drag and Drop
Java2D
CORBA
JNDI
Java Sound
Timer
Regular ExpLoggingAssertionsNIO
Java 1.5.0 (called as “Tiger”)
J2SDK 1.5 / J2SDK 5.0 version Focused on below key areas
Ease of Development Scalability, Performance and quality Monitoring and Manageability Desktop Client Miscellaneous Features
What’s New
J2SE 5.0 is full of dramatic changes to the java programming language, including new syntax support and JVM enhancements.
It is considered to be the most revolutionary java release since JDK1.2
New Features in J2SE 5.0 Language Features (Enhanced for Loop, Static Import, Type-safe enumerations,
Boxing / Unboxing, Annotations (aka metadata), Variable Arguments, Generics)
Virtual Machine Features (Class Data Sharing, Server-Class Machine Detection, Garbage
Collector Ergonomics, Thread Priority Changes, High-Precision Timing Support)
Performance Enhancements (Garbage collection Ergonomics, StringBuilder Class, Java 2D
Technology, Image I/O)
Base Libraries (Lang and Util Packages, Networking, JAXP, Bit Manipulation
Operations) Integration Libraries (Remote Method Invocation (RMI), Java Database
Connectivity (JDBC), Java Naming and Directory Interface (JNDI))
Scanner and Formatter - printf() method Finally, simplified input and formatted output
Enhanced for loop Automates use of Iterators to avoid errors
Static import - import static java.Math.*; Lets you avoid qualifying static members with class names
Enumerated Types Provides all the well-known benefits of the Typesafe Enum
pattern
Autoboxing / Unboxing Automatic wrapping and unwrapping of primitives
Generic Types Compile-time type safety for collections without casting
Java 1.5 New Features
Metadata Variable length argument lists. Semaphores Many more features and
enhancements Improved performance
Java 1.5 New Features
New features enhance existing API
Static import improves utility functions Enum improves readability and organization
of constants Auto-boxing improves readability Generics enhance compile time type
checking Generics improve reflection Generics allow return type overriding
§2. Formatted I/O
Scanner class Provides basic input functionality for reading data
from system console or any data stream Following example reads a String from standard input
and expects a following int value:Scanner s= new Scanner(System.in); String param= s.next(); int value=s.nextInt(); s.close();
Scanner methods next and nextInt block if no data is available
Supports regular expression based search To process more complex input, pattern matching
algorithms are available from class java.util.Formatter
java.util.Scanner
Java finally has a fairly simple way to read input Scanner sc = new Scanner(System.in); boolean b = sc.nextBoolean(); byte by = sc.nextByte(); short sh = sc.nextShort(); int i = sc.nextInt(); long l = sc.nextLong(); float f = sc.nextFloat(); double d = sc.nextDouble(); String s = sc.nextLine();
By default, whitespace acts as a delimiter, but you can define other delimiters with regular expressions
ScannerScanner API provide a more robust mechanism for reading in data
types rather than simply parsing strings from buffered System.in calls. Prior to Scanner feature was introduced, to read from standard input it would be necessary to write exception handling code and wrap an InputStreamReader and a BufferedReader around System.in. Scanner class throws an unchecked exception InputMismatchException, which you could optionally catch.
Scanner API simplifies your code as follows:
Scanner keyboard = new Scanner(System.in); //no more wrapping with InputStreamReader and //BufferedReader around System.inSystem.out.println("Enter your first number?");int i1 = keyboard.nextInt(); //no more parsing strings e.g. new Integer("5").intValue();System.out.println("Enter your second number?");int i2 = keyboard.nextInt(); //no more parsing strings e.g. new Integer(str).intValue();
Improved input
The new Scanner class can parse primitive types and strings using regular expressions The Scanner class can also read in input from
a String (not just an I/O stream)
Formatted output
Similar to C/C++ printf and scanf:System.out.printf("name count%n"); //newlineSystem.out.printf("%s %5d%n", user,total);
Supports formats for dates, etc:System.out.format("Local time: %tT",Calendar.getInstance()); // -> "Local time: 13:34:18"
Like C's sprintf(3), Strings may be formatted using String.format: import java.util.Calendar; import java.util.GregorianCalendar; import static java.util.Calendar.*; Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke's Birthday: May 23, 1995"
java.util.Formatter
Java now has a way to produce formatted output, based on the C printf statement
String line;int i = 1;while ((line = reader.readLine()) != null) { System.out.printf("Line %d: %s%n", i++, line);}
There are about 45 different format specifiers (such as %d and %s), most of them for dates and times
C-style printf()method
C-style printf() Uses a variable number of arguments
(“varargs”). Formatting options for each argument.
Common formats for numeric, string, and date/time.
Layout justification and alignment. Locale-specific output
Normally used with System PrintStream System.out System.err
printf()method example
System.out method call to printf():
System.out.printf(“%d %.2f %.2e\n", 78, 1.23456, 1.23456);
will print:
78 1.23 1.23e+00
printf()method -numeric examples
Format Value Output
“%.2f” 1.23456 1.23
“%.2e” 1.23456 1.23e+00
“%,15.2f” -234567.8 -234,567.80
“%(,15.2f” -34567. (34,567.00)
“%x” 252 fc
“%4d” 5 5
“%04d” 78 0078
printf()method -alignment examplesFormat Value(s) Output
“%10s” “ABC” ABC
“%-10s” “ABC” ABC
“%10d” 123 123
“%-10d” 123 123
“%-10s %-2s %05d-%04d”
“Hartford”, “CT”, 6115, 11
Hartford CT06115-0011
printf()method -Date (02/23/2004) examplesFormat Output
“%tD” 02/23/04
“%tF” 2004-02-23
“%1$tb %1$te %1$ty” Feb 23 04
“%1$tA %1$tB %1$te, %1$tY”
Monday February 23, 2004
“%1$tF %1$tr” 2004-02-23 10:45:00 AM
Formatter class
Same C-style printf()capability Variable number of arguments (“varargs”) Same formatting options as printf().
Used with: String File
Code similar to output streams. Not everyone sends output to:
System.out and System.err e.g., servlet output to web pages.
Formatter class example
Formatter formatter = new Formatter();formatter.format( "%-10s %-2s ","Hartford","CT");
formatter.format( "%05d-%04d",6115,11);
String s = formatter.toString();
formatter.close();
s now contains:
Hartford CT 06115-0011
Improved output
The new Formatter class, modeled after C’s printf statement, gives you much simpler formatted output This class provides support for:
Layout justification and alignment Common formats for numeric, string, and date/time
data Locale-specific output Common Java types such as byte, BigDecimal, and
Calendar Limited formatting customization for arbitrary user
types is provided through the Formattable interface
§3. Enhanced for Loop
Iterators An iterator gives you every element of a
collection, one at a time The collection has a type iterator(); factory method to
return a new iterator to return objects of the given type The method boolean hasNext() tells you if there are
more objects The method type next() returns the next object The method void remove() deletes the last object
gotten Example:
Iterator iter = integerStack.iterator();while (iter.hasNext()) { System.out.println(iter.next());}
New for statement
The syntax of the new statement is for(type var : array) {...}or for(type var : collection) {...}
Example: for(float x : myRealArray) { myRealSum += x; }
For a collection class that has an Iterator, instead of for (Iterator iter = c.iterator(); iter.hasNext(); ) ((TimerTask) iter.next()).cancel();you can now say for (TimerTask task : c) task.cancel();
Iterations, Part I
List policies = new ArrayList(); . . .Iterator iter = policies.iterator();while ( iter.hasNext() ) { renew( (Policy)iter.next() );}
A common Java “idiom” for iteration. Is this the best way to iterate through a
collection?
Iterations, Part II
List policies = new ArrayList();
. . .
for (Iterator iter = policies.iterator(); iter.hasNext(); ) {
renew( (Policy)iter.next() );
}
Another common Java “idiom” for iteration. Is this any better?
Iterations, Part III
How about iterating through arrays?
Policy policies[] = { … };
. . .
for ( int i = 0; i < policies.length; ++i ) {
renew( policies[i] );
}
Is looping through an array any better?
Enhanced for loop
Iterations over collections are painful. Iterator is only used to get elements. Iterators can be error-prone.
Iterator variable used in for loop three times – two opportunities to get it wrong.
Common cut and paste errors. A “foreach” style loop construct would be
better. Wouldn’t it be nice if the compiler
would iterate for you?
Enhanced for loopfor Collections For collections:
List policies = new ArrayList();
. . .
for ( Object policy : policies ) {
renew( (Policy)policy );
}
Using the enhanced for loop is much clearer.
But, note the cast to Policy.
Enhanced for loopfor Arrays For arrays:
Policy[] policies = { … };
. . .
for ( Policy policy : policies ) {
renew( policy );
}
Again, using the enhanced for loop is clearer.
And, no cast is needed to Policy.
Enhanced for loop Restrictions
Restrictions Cannot be used to filter a collection.
i.e., remove elements Cannot modify the current slot in an array or list.
e.g., replace the entire element Provides for most common for loop “idiom”.
Provides simple iteration over a collection or an array.
More complicated processing addressed by the traditional for or while loops.
J2SE 1.4.0for(Iterator iter = myArray.iterator(); iter.hasNext(); ) {
MyClass myObj = (MyClass)iter.next();
myObj.someOperation(); }
J2SE 5.0
for(MyClass myObj : myArray) {
myObj.someOperation();}
// Returns the sum of the elements of aint sum(int[] a) {
int result = 0;for (int i : a)
result += i;return result;
}
For Arrays
● Eliminates array index rather than iterator● Similar advantages
For Each Statement A great way to ditch annoying Iterators.
Makes code more elegant and less error prone.
before
after
Spot the Bug
Fixed Version
Using the For Each Statement
For each loop (arrays)
double[] array = {2.5, 5.2, 7.9, 4.3, 2.0};
for(double d: array) {
System.out.println(d); }
Iterate (forward) through the array without paying attention to indices.
For each loop (Collections)ArrayList<Integer> list = new
ArrayList<Integer>(); list.add(7); list.add(15); list.add(-67); for(Integer number: list)
{ System.out.println(number); }
For each loop enums
for( Suit s: Suit.values()){System.out.println(s.getColor());
}
values() returns an Iterator for enum types
§4. Static Imports
The “Constant Interface” antipattern
public interface Physics { public static final double AVOGADROS_NUMBER = 6.02214199e23; public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; public static final double ELECTRON_MASS = 9.10938188e-31;}
public class Guacamole implements Physics { public static void main(String[] args) { double moles = ...; double molecules = AVOGADROS_NUMBER * moles; ... }}
This is considered to be very poor style by smart programmers who have thought about it a lot more than I have
Static Import You can now import just the static members of a class or interface public interface Physics { // as before
public static final double AVOGADROS_NUMBER = 6.02214199e23; public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; public static final double ELECTRON_MASS = 9.10938188e-31;}
import static org.iso.Physics.*;
class Guacamole { public static void main(String[] args) {
double moles = ...; double molecules = AVOGADROS_NUMBER * moles; ... }}
Static Import
Enables one to refer to static constants from a class without needing to inherit from it
If only used on occasion this technique is not very useful, but in complex cases this technique help simplify coding
Example
import static java.awt.BorderLayout.*;
import static java.lang.System.*;
getContentPane().add(new JPanel(), CENTER);
Out.println(“hello world”);
Static Import
import static java.lang.Math.*;…int themax = max( 123123, 23475 );
Reduces typing Alleviates need for implementing a
Constant Interface Compiler error if names clash
Static Import
Static imports let you avoid qualifying static members with class names. Once the static member is imported then you can use it in your code without the class name prefix.
//static importimport static sample.SampleStaticValues.NUM_ZERO;…//need not do SampleConstants.NUM_ZERO due to static import
featureif(num % 2 == NUM_ZERO){System.out.println("The num " + num + " is: " + OddEven.even);}package sample;public class SampleStaticValues {public static int NUM_ZERO = 0;public static int NUM_ONE = 0;}
Static Import
In order to access static members, it is necessary to qualify references with the class they came from.
double r = Math.cos(Math.PI * theta);
As a workaround people often put static members as part of an interface and inherit from that interface.
This is known as the “Constant Interface Antipattern”
Static Import
Using constants of another class is merely an implementation detail. Declaring that a class implements an interface is an API issue. Implementation details should not leak into APIs.
The static import construct allows you to access static members of another class without inheriting from the type containing them.
Static Import
members of another class are importedimport static java.lang.Math.PI;
Once imported they can be used without qualification
double r = cos(PI * theta);
Example
BeforeSystem.out.println(“Hello”);
System.out.println(“World”);
System.err.println(“From”);
System.err.println(“Me”);
Afterimport static java.lang.System.*;
out.println(“Hello”);
out.println(“World”);
err.println(“From”);
err.println(“Me”);
Static Vs. Normal import
Static imports are analogous to regular imports. In normal imports you import classes from packages, and in static imports you import static class members out of classes.
Use with care: only when frequent access is required. It is suppose to improve readability, and overuse may have an opposite effect.
Static import
Ability to access static members from a class without need to qualify them with a class name.
interface ShapeNumbers { public static int CIRCLE = 0; public static int SQUARE = 1; public static int TRIANGLE = 2;
}
Implementing this interface creates an unnecessary dependence on the ShapeNumbers interface.
It becomes awkward to maintain as the class evolves, especially if other classes need access to these constants also and implement this interface
To make this cleaner, the static members are placed into a class and then imported via a modified syntax of the import directive.
package MyConstants; class ShapeNumbers {
public static int CIRCLE = 0; public static int SQUARE = 1; public static int TRIANGLE = 2;
}
To import the static members in your class, specify the following in the import section of your Java source file.
import static MyConstants.ShapeNumbers.*; // imports all static data
You can also import constants individually by using the following syntax:
import static MyConstants.ShapeNumbers.CIRCLE;import static MyConstants.ShapeNumbers.SQUARE;
An example of importinga Java class For example, to use java.lang.Math.
double radians = Math.toRadians(30.0);
double unity = Math.pow(Math.sin(radians),2.0) + Math.pow(Math.cos(radians),2.0);
double areaCircle = Math.PI * Math.pow(10.0,2.0);
Importing Static Members
Currently Importing a class or interface
Why require a class name prefix?
Static Import A variant of the import statement. Import static methods and fields. Similar to the import of classes and
interfaces from a package. Import individual members, or
collectively.
With Static Import
No need to reference Math, except in import.
import static java.lang.Math.*;
double radians = toRadians(30.0);
double unity = pow(sin(radians),2.0) + pow(cos(radians),2.0);
double areaCircle = PI * pow(10.0,2.0);
Importing Static Members
Code is more readable. No need to reference the class or
interface names. Code can be less understandable.
No reference to class or interfaces names.
Implementation detail added. Commitment to the implementation.
Static import facility import static org.iso.Physics.*;
class Guacamole { public static void main(String[] args) { double molecules = AVOGADROS_NUMBER * moles; ... }}
You no longer have to say Physics.AVOGADROS_NUMBER
Are you tired of typing System.out.println(something); ?
Do this instead: import static java.lang.System.out; out.println(something);
§5. Enumeration Types
Enumerations
An enumeration, or “enum,” is simply a set of constants to represent various values
Here’s the old way of doing it:public final int SPRING = 0;public final int SUMMER = 1;public final int FALL = 2;public final int WINTER = 3;
This is a nuisance, and is error prone as well
Here’s the new way of doing it:enum Season { winter, spring, summer, fall }
enums are classes An enum is actually a new type of class
You can declare them as inner classes or outer classes You can declare variables of an enum type and get type safety
and compile time checking Each declared value is an instance of the enum class Enums are implicitly public, static, and final You can compare enums with either equals or ==
enums extend java.lang.Enum and implement java.lang.Comparable Hence, enums can be sorted
Enums override toString() and provide valueOf() Example:
Season season = Season.WINTER; System.out.println(season ); // prints WINTER season = Season.valueOf("SPRING"); // sets season to Season.SPRING
Enums really are classes
public enum Coin { // enums can have instance variables
private final int value; // An enum can have a constructor, but it isn’t
public Coin(int value) { this.value = value; }
// Each enum value you list really calls a constructor PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
// And, of course, classes can have methods public int value() { return value; }}
Other features of enums
values() returns an array of enum values Season[] seasonValues = Season.values();
switch statements can now work with enums switch (thisSeason) { case SUMMER: ...; default: ...} You must say case SUMMER:, not case
Season.SUMMER: It’s still a very good idea to include a default case
It is possible to define value-specific class bodies, so that each value has its own methods The syntax for this is weird, and I don’t yet understand
it well enough myself to lecture on it
Standard Approach to Constant Enumerations – Definition int enums
public class PolicyOperation { public static final int QUOTE = 1; public static final int ISSUE = 2; public static final int RENEW = 4; public static final int CANCEL = 12; public static final int ENDORSE = 16; public static final int CHANGE = 64; public static final int REINSTATE = 192; . . .
Simple example of Typesafe enum Construct For a deck of cards…
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
enum Rank { DUECE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
List<Card> deck = new ArrayList<Card>();
for ( Suit s: Suit.values() )
for ( Rank r: Rank.values() )
deck.add(new Card(s,r));
A more complex Typesafe enum Construct
public enum OperationEnum { QUOTE(1), ISSUE(2), RENEW(4), CANCEL(12),
ENDORSE(16), CHANGE(64), REINSTATE(192); private int operation = 0; private OperationEnum(int op) { this.operation = op; } public boolean isNewOperation() { return (this.operation==2) || (this.operation==4) || (this.operation==192); }}
Using the Typesafe enum Construct
void process(OperationEnum oper) {
. . .
switch (oper) {
case ISSUE: . . .
case CANCEL: . . .
}
// Prints “ISSUE”, not “1”
System.out.println(oper);
}
Type Safety: All statuses above may carry some business meaning, but in Java language context, these are just int values. This means any int value is a status for this Java program. So the program using these statuses can break with any int value not defined in this group.
Type-safe enumerations
Compiler support for Typesafe Enum pattern.
Looks like traditional enum (C, C++, Pascal).
Far more powerful. Can be used in switch/case
statements. Can be used in for loops.
An enumeration is an ordered list of items wrapped into a single entity.
enum Season {winter, spring, summer, fall}
Usage Examplefor (Season s : Season.VALUES){
//}
An enumeration (abbreviated enum in Java) is a special type of class.
All enumerations implicitly subclass a new class in Java, java.lang.Enum.
This class cannot be subclassed manually.
Enums
Previously, the standard way to represent an enumerated type was to use the int Enum pattern:
public static final int WINTER = 0;
public static final int SPRING = 1;
public static final int SUMMER = 2;
public static final int FALL = 3;
Switch with EnumColor getColor( Suit suit ) {
switch( suit ) {
case clubs:
case spades: return Color.Black;
case diamonds:
case hearts: return Color.Red;
default: throw new AssertionError( suit + “ not valid value” );
}
}
Enumerated Types
Similar to enum types in C, Pascal etc. and HashTable, keyset
Enums are classes, extends java.lang.Enum Class declaration:
Class Enum<E extends Enum<E>> Enums are final, can’t be subclassed. Only one Constructor and is are protected. Implement java.lang.Comparable:
compareTo() Implement Serializable
Fun with Enums public enum DAYConstants {
MON<,UES<WED………..
}; Class DAYConstants { Final staic sting MONDAY = 1; TUESDAY = 2;
doStuff(52); }
Pubilc int doStuff(DAYConstants day) {
}
Enumerated types Enumerated types are a way of representing nonstandard
data, such as days of the week, with integers: static final int SUNDAY = 1;
static final int MONDAY = 2;…
Or months of the year: static final int JANUARY = 0;
static final int FEBRUARY = 1;…
The problem with this approach is that there are so many ways to make errors: static final int DECEMBER = 12; int date = year + month + dayOfWeek;
Over the past few years there have been many attempts to define an idiom for making type-safe enumerations
Enumerated types in Java 1.5
public enum Suit {clubs, diamonds, hearts, spades} Notice new keyword “enum” Values of enum constants are assigned automatically public enum Coin{
penny(1), nickel(5), dime(10), quarter(25); // values Coin(int value) { this.value = value; } // constructor private final int value; // instance
variable public int value() { return value; } // method
} This is very like a class declaration
Printing results in the named constant: dime, not 10
Named constants can be read in
Using an enumerated type public class CoinTest {
public static void main(String[] args) { for (Coin c : Coin.VALUES) System.out.println(c + ": \t" + c.value() +"¢ \t" + color(c)); }
private enum CoinColor { copper, nickel, silver }
private static CoinColor color(Coin c) { switch(c) { case Coin.penny: return CoinColor.copper; case Coin.nickel: return CoinColor.nickel; case Coin.dime: // deliberate fall through to next case case Coin.quarter: return CoinColor.silver; default: throw new AssertionError("Unknown coin: " + c); } }}
Advantages of enumerated types
enum types simplify code and make it more readable Types are checked at compile time (hence, very type safe) Performance is comparable to int constants Each enum type has its own name space (you don't have to say
Coin.dime) You can add, reorder or even remove constants without the need to
recompile other classes that use these constants I’ve seen one source that says you do need to recompile
Printed values are informative enum constants can be used in collections (for example, as HashMap
keys) You can add arbitrary fields and methods to an enum class An enum type can be made to implement arbitrary interfaces enum types can be used in switch statements enum types are serializable
Disadvantages of enumerated types
Still more complexity in the language Harder for beginners, nicer for experts!
Type-safe enum
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }
//usedDay today = Day.WEDNESDAY;
switch(today){case SUNDAY:
break;//…
}
More Complex Enum
enum Suit { CLUBS(Color.BLACK), DIAMONDS(Color.RED), HEARTS(Color.RED), SPADES(Color.BLACK);
private Color color;
Suit(Color color) { this.color = color; }
public Color getColor() { return color; } }
§6. Autoboxing / Unboxing
Autoboxing Java distinguishes between primitive types and
Objects Primitive types, i.e., int, double, are compact, support
arithmetic operators Object classes (Integer, Double) have more methods:
Integer.toString() You need a “wrapper” to use Object methods:
Integer ii = new Integer( i ); ii.hashCode() Similarly, you need to “unwrap” an Object to use primitive
operationint j = ii.intValue() * 7;
Java 1.5 makes this automatic: Before:
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, new Integer(42)); int total = (list.get(0)).intValue();
After:ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, 42); int total = list.get(0);
Auto boxing and unboxing
Java won’t let you use a primitive value where an object is required--you need a “wrapper” myVector.add(new Integer(5));
Similarly, you can’t use an object where a primitive is required--you need to “unwrap” it int n = ((Integer)myVector.lastElement()).intValue();
Java 1.5 makes this automatic: Vector<Integer> myVector = new Vector<Integer>();
myVector.add(5);int n = myVector.lastElement();
Other extensions make this as transparent as possible For example, control statements that previously required a
boolean (if, while, do-while) can now take a Boolean There are some subtle issues with equality tests, though
www.themegallery.com
Autoboxing / Unboxing Example Traditional “boxing” example:
List ssnList = new ArrayList();
. . .
int ssn = getSocSecNum();
. . .
Integer ssnInteger = new Integer(ssn);
ssnList.add(ssnInteger);
Why do I have to convert from int to Integer?
Autoboxing / Unboxing Example #1 “Autoboxing” example:
List ssnList = new ArrayList();
. . .
int ssn = getSocSecNum();
. . .
ssnList.add(ssn);
No need for an explicit conversion to Integer.
Autoboxing / Unboxing
The need to explicitly convert between primitive types and wrapper objects. Such as primitive type int, and wrapper object Integer.
Can’t put primitives into Collections. Autoboxing and Unboxing
Automatic conversion by the compiler Eliminates casts Automatically part of method invocation,
assignment conversion, numeric promotion. Wouldn’t it be nice if the compiler would
perform these conversions for you?
Autoboxing / Unboxing Example #2 Autoboxing/Unboxing used in other
ways.
double area(double height, double width) { return height * width;
} . . .
Double h = new Double(…); double w = …; double a = area(h,w); Double A = area(h,w);
Autoboxing / Unboxing Example #3 And others:
Double premium = new Double(123.45);
Double tax = premium * 0.05;double fee = 5.95;Double totalPremium = premium + tax + fee;
This is an example. Mixing primitives and objects. (Note: Don’t multiply two floating point values and
expect to get an accurate result!)
Boxing / Unboxing
Collections hold only objects, so to put primitive data types it needs to be wrapped into a class, like int to Integer.
It is a pain to wrap and unwrap. Wouldn’t it be nice if the compiler
took care of it for you?
J2SE 1.4.0
ArrayList arrayList = new ArrayList(); Integer intObject = new Integer(10);arrayList.add(intObject); // cannot add 10 directly
J2SE 5.0
ArrayList arrayList = new ArrayList(); arrayList.add(10); // int 10 is automatically wrapped into Integer
Autoboxing and Unboxing
Autoboxing: Automatic converting of primitives into wrapper
classes
Integer x = 10;
Unboxing Automatic converting of wrapper classes into
primitives
double PI = new Double(3.14);
§7. Improvement / Performance
Analyze Memory Heap Dump
Any problem in pure Java code throws a Java exception or error. Java exceptions or errors will not cause a core dump (on LINUX systems) or a Dr.Watson error (on WIN32systems). Any serious Java problem will result in an OutOfMemoryError thrown by the JVM with the stack trace and consequently JVM will exit. These Java stack traces are very useful for identifying the cause for an abnormal exit of the JVM. So is there a way to know that OutOfMemoryError is about to occur? The Java JDK 1.5 has a package called java.lang.management which has useful JMX beans that we can use to manage the JVM. One of these beans is the MemoryMXBean.
StringBuilder Class Introduced a new class java.lang.StringBuilder. It is like unsunchronized StringBuffer. Faster than StringBuffer. An improvement upon StringBuffer Allows quicker concatenation of strings. Why use it?
Creating new Strings in a loop can be inefficient because of the number new objects that are created and discarded.
StringBuilder.append(<type> <value>) StringBuilder.insert(<type> <value>)
No synchronization! Not safe for use by multiple threads
Performance
Faster startup time
Better garbage collection; low pause option
§8. Complementary Features
Complementary Features
Generics improve enhanced for loop Generics and auto-boxing/unboxing
allow Enumerated types Variable args improve API usability Variable args allow formatted I/O
§9. Final Comments
"The new language features all have one thing in common: they take some common idiom and provide linguistic support for it. In other words, they shift the responsibility for writing the boilerplate code from the programmer to the compiler."
Final Comments
Better expressiveness Current Java “idioms”
Java “boilerplate” code New language features
Shift boilerplate code from programmer to compiler. Easier to write. Reduces the chances for bugs. Easier to read. Less code to accomplish the same
result.
Increased type safety Catch bugs at compile time, not run time.
If you have any queries, Please feel free to contact meEmail – [email protected]