YOUR FEEDBACK
Cloud Computing: Do You Really Want Your Data in the Cloud?
Don Dodge wrote: D Cheng, Of course in-house systems go down. What I am sa...
AJAXWorld RIA Conference
$300 Savings Expire July 25
Register Today and SAVE!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP LINKS YOU MUST CLICK ON


Java Developer's Journal: "Developing in Java 5"
How to use the new set of tools wisely

Digg This!

Page 2 of 2   « previous page

You could also use an interface for the same purpose. This is common, but it's debatable whether it's a good idea to do so.

This implementation has many problems. Since the constants are just ints, it's easy to pass out-of-range values to methods. There is nothing to prevent you from passing these constants to methods they weren't designed for.

For example:


public class Card {
public Card (int suit, int rank) {
...
}
}
You can write something like new Card(KING,HEARTS) and you won't find out that something is wrong until runtime.

It's possible to use the "typesafe enum" pattern (for example, see the book Effective Java by Joshua Bloch) in JDK 1.4 to overcome these problems, but it requires a lot of boilerplate code, and the resulting classes have a fatal flaw, from the developer's point of view: you cannot switch on this kind of enum, so any switch-like code becomes very clunky.

J2SE introduces the enum keyword to specify first-class enumerated types. Here is simple example code:


public enum RegularPolygon {
TRIANGLE,
SQUARE,
PENTAGON;
}
A significant advantage of the enum construct (compared to handcrafted enumerations) is that enums are full-fledged Java classes, so they can have constructors, fields, and methods. For example:

public enum RegularPolygon {
TRIANGLE(3),
SQUARE(4),
PENTAGON(5);
final int numSides;

RegularPolygon (int sides) {
numSides = sides;
}
public double perimeter (double sideLength) {
return sideLength * numSides;
}
}
Client code can switch on the enum:

public computeArea(RegularPolygon p, double side) {
switch (p) {
case Polygon.TRIANGLE:
return side * side * Math.sqrt(3) / 4;
case Polygon.SQUARE:
return side * side;
case Polygon.PENTAGON:
return side * side * 1.72;
default:
System.err.println("Unknown polygon");
return 0;
}
}
The default case in the switch is used in case someone adds a new polygon to the enum.

Class Libraries
J2SE 5 introduces several utility classes that can make your life easier, but you obviously won't gain any benefits from them unless you actually use them. It is almost always a mistake to write your own implementation of a data structure or a method that is present in the Java class library. The base Java implementation is very likely to be better thought-out and less buggy than an implementation that you would come up with. Here are a few new additions to the Java class libraries that may prove useful.

Queue and Implementations
java.util.Queue is a new interface that has been added to the Collections framework. LinkedList now implements the Queue interface and models a simple FIFO queue. Another implementation you may find useful is PriorityQueue.

ProcessBuilder
The ProcessBuilder class provides a significantly easier way to launch and control applications than Runtime.exec() does. The following code will launch Eclipse on a Linux machine from a specified directory and display its window on the main display of the machine called italy.


String home = System.getProperty("user.home");
ProcessBuilder builder = new ProcessBuilder (
"./eclipse", "-data", home + "/workspace");
builder.directory(new File(home + "/eclipse"));
builder.environment().put("DISPLAY", "italy:0.0");
builder.start();
Formatter The Formatter class and its cousin methods String.format() and PrintStream.printf() provide a straightforward and powerful way to finely format strings and output. If you are familiar with the C printf and sprintf functions, it should be easy to use the new class and methods. For example, the following code will print out an amount of money using the correct padding if the cents are a one-digit number:

public static void dollarFormat (int dollars, int cents) {
System.out.printf("$%d.%02d", dollars, cents);
}
Scanner
The Scanner class provides an easy way to extract strings and primitives from a formatted stream. By default, it uses white space for field delimiters, but it's easy to configure it to use any regular expression as a delimiter. J2SE 1.4 classes and methods such as StringTokenizer, String.split(), and Integer.parseInt() could cover some of the functionality that the Scanner class provides, but the new class is more flexible and powerful. The following code will echo lines from System.in to System.out, as long as they can be parsed as integers:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
Conclusion
Often, being a programmer is much like being a carpenter. To do a job well, you need to know which tools are available and which one is best suited for the job at hand. J2SE 5 provides a set of new tools that you can add to your Java development tool belt. Use them wisely, and you will spend more time thinking about how your code hangs together and less writing boilerplate and tracking down bugs.

References


Page 2 of 2   « previous page

About Roberto Scaramuzzi
Roberto Scaramuzzi is a software engineer at Parasoft. He grew up professionally as a Perl developer, but is now also adept at Java and PHP. Roberto holds a PhD in mathematics.

Java Developer's Journal News Desk wrote: 'Ease of Development' is one of the main focuses in J2SE 5. Accordingly, J2SE 5 introduces several new features designed to simplify the developer's life. If you use these new constructs, your code will become more compact and expressive, hence easier to understand and debug. This article explains how you can use the new features to prevent some silly mistakes, as well as some that are not so silly.
read & respond »
LATEST ECLIPSE STORIES . . .
Adobe's Kevin Lynch and Microsoft's Scott Guthrie to Keynote AJAX World RIA Conference & Expo
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be
Virtualization Conference Keynote Webcast Live on SYS-CON.TV
Brian Stevens, the Chief Technology Officer and Vice President of Engineering of Red Hat, delivered his Virtualization Keynote 'The Future of the Virtual Enterprise' at SYS-CON's Virtualization Conference & Expo 2007 West in San Francisco. 'Virtualization is the hottest subject today,
Java GUI Squish Supports New Eclipse Ganymede 3.4
Squish for Java is a leading functional GUI and regression testing tool enabling the creation and execution of automated GUI tests for Java SWT/RCP and AWT/Swing applications.
Instantiations Rolls Out Product Updates in Conjunction with Eclipse 3.4 and Ganymede
Instantiations announced that its entire Eclipse-based product line has been updated to coincide with the annual Eclipse open source release, Ganymede. Included with the roll-out are additions in the area of security to its CodePro AnalytiX comprehensive code quality product, bringing
Quest Software's JProbe Now Available as Eclipse Plug-In
Quest Software announced the latest release of its Java profiler, JProbe 8.0, which is now offered as a plug-in to the Eclipse Java Integrated Development Environment (IDE). The release of this capability aligns with the increased adoption of the open source development. Launching JPro
Migrate to Eclipse 3.4 Ganymede, Manage Configurations with Pulse
Genuitec announced the general availability of Pulse 2.2, a way to obtain, manage and configure Eclipse Ganymede and plugins. Genuitec is pleased to offer this product to Pulse users on the day of the Ganymede release. As of today, Pulse 2.2 will support full Ganymede tool stacks.
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE