Thursday, July 22, 2010

Formatter Class in J2SE 1.5

Java 1.5 introduces a new class named java.util.Formatter that allows you to do string formatting similar to the printf function in C. It depends heavily on the varargs feature being introduced in 1.5

System.out.printf

String initials = "rk";
String comment = "just because";
System.out.printf("reason: %s (noted by %s)", comment, initials);

The example prints the following output on the console:

reason: just because (noted by rk)

----------------
String.format

If you only want to obtain a formatted string, but not print it, you can use the static method format on the String class. Here's an example that also demonstrates a few numeric conversions:

int a = 65;
String s =
String.format("char: %c integral: %d octal: %o hex: %x %n",
a, a, a, a);

The %n at the end of the format string indicates a platform-specific line separator. When printed, the String s looks like this:

char: A integral: 65 octal: 101 hex: 41

Numeric conversions also support flags for padding, grouping, justification, and sign.
-----------------------
Dates

Formatter provides an extensive number of date-related conversions. The following code:

String.format("%1$td %1$tb %1$ty", new Date())

produces a string with the value:

26 Feb 04

-----------------------------------------
java.util.Formatter

The Formatter class is at the core of the new formatting capability. It fully supports internationalization by letting you pass a Locale to the constructor; the other formatting methods (e.g. String.format) also allow this.

Formatter also lets you pass an Appendable object. This is a new interface that defines append methods so that the formatter can store its results in a text collector such as a stream object. Sun has modified all relevant Java classes, such as StringBuffer and PrintStream, to implement this interface. Here's how you might use it:

double avogadro = 6.0e23;
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
formatter.format("avogadro's number: %e %n", avogadro);
formatter.format("base of the natural log: %e %n", Math.E);
System.out.println(buffer.toString());

The corresponding output:

avogadro's number: 6.000000e+23
base of the natural log: 2.718282e+00

No comments:

Post a Comment