Formatter
With the release of JDK 5, Java added a capability long desired by programmers: the ability to
easily create formatted output. Since the beginning, Java has offered a rich and varied API, but
it had not always offered an easy way to create formatted text output, especially for numeric
values. Classes such asNumberFormat,DateFormat, andMessageFormatprovided by earlier
versions of Java do have useful formatting capabilities, but they were not especially convenient
to use. Furthermore, unlike C and C++ that support the widely understood and usedprintf( )
family of functions which offers a simple way to format output, Java had previously not offered
such methods. One reason for this is thatprintf-style formatting requires the use of
variable-length arguments (varargs), which Java did not support until the release of JDK 5. Once
varargs were available, it was a simple matter to add a general-purpose formatter.
At the core of Java’s support for creating formatted output is theFormatterclass. It provides
format conversionsthat let you display numbers, strings, and time and date in virtually any
format you like. It operates in a manner similar to the C/C++printf( )function, which means
that if you are familiar with C/C++, then learning to useFormatterwill be very easy. It also
further streamlines the conversion of C/C++ code to Java. If you are not familiar with C/C++,
it is still quite easy to format data.
NOTEOTE Although Java’sFormatterclass operates in a manner very similar to the C/C++printf( )
function, there are some differences, and some new features. Therefore, if you have a C/C++
background, a carefulreading is advised.
Chapter 18: java.util Part 2: More Utility Classes 525
Method Description
String getCurrencyCode( ) Returns the code (as defined by ISO 4217) that describes
the invoking currency.
int getDefaultFractionDigits( ) Returns the number of digits after the decimal point that
are normally used by the invoking currency. For example,
there are 2 fractional digits normally used for dollars.
static Currency
getInstance(LocalelocaleObj)
Returns aCurrencyobject for the locale specified by
localeObj.
static Currency
getInstance(Stringcode)
Returns aCurrencyobject associated with the currency
code passed incode.
String getSymbol( ) Returns the currency symbol (such as $) for the invoking
object.
String getSymbol(LocalelocaleObj) Returns the currency symbol (such as $) for the locale
passed inlocaleObj.
String toString( ) Returns the currency code for the invoking object.
TABLE 18-10 The Methods Defined byCurrency