Chapter 18: java.util Part 2: More Utility Classes 529
// A very simple example that uses Formatter.
import java.util.*;
class FormatDemo {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("Formatting %s is easy %d %f", "with Java", 10, 98.6);
System.out.println(fmt);
}
}
One other point: You can obtain a reference to the underlying output buffer by calling
out( ). It returns a reference to anAppendableobject.
Now that you know the general mechanism used to create a formatted string, the remainder
of this section discusses in detail each conversion. It also describes various options, such as
justification, minimum field width, and precision.
Formatting Strings and Characters
To format an individual character, use%c. This causes the matching character argument to
be output, unmodified. To format a string, use%s.
Formatting Numbers
To format an integer in decimal format, use%d. To format a floating-point value in decimal
format, use%f. To format a floating-point value in scientific notation, use%e. Numbers
represented in scientific notationtake this general form:
x.dddddde+/âyy
The%gformat specifier causesFormatterto use either%for%e, whichever is shorter.
The following program demonstrates the effect of the%gformat specifier:
// Demonstrate the %g format specifier.
import java.util.*;
class FormatDemo2 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for(double i=1000; i < 1.0e+10; i *= 100) {
fmt.format("%g ", i);
System.out.println(fmt);
}
}
}