Java Reference
In-Depth Information
System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 1, 10, 100);
System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 10, 100, 1000);
// Formatting date and time
Date dt = new Date();
System.out.printf("Today is %tD %n", dt);
System.out.printf("Today is %tF %n", dt);
System.out.printf("Today is %tc %n", dt);
}
}
Fu, Hu, and Lo
Lo, Hu, and Fu
1, 10, 100
10, 100, 1000
1, 10, 100
10, 100, 1000
Today is 01/24/14
Today is 2014-01-24
Today is Fri Jan 24 21:41:20 CST 2014
You have been using the
System.out.println()
and
System.out.print()
methods to print text on the standard
output. In fact,
System.out
is an instance of the
java.io.PrintStream
class, which has
println()
and
print()
instance methods. Java 5 added two more methods,
format()
and
printf()
, to the
PrintStream
class, which can be
used to write a formatted output to a
PrintStream
instance. Both methods work the same. Listing 13-5 uses
System.out.printf()
method to print the formatted text to the standard output.
Java 5 also added a
format() static
method to the
String
class, which returns a formatted string. The
formatting behavior of the
format()
/
printf()
method of the
PrintStream
class and the
format() static
method
of the
String
class is the same. The only difference between them is that the
format()/printf()
method in the
PrintStream
class writes the formatted output to an output stream, whereas the
format()
method of the
String
class
returns the formatted output.
The
format()
/
printf()
method of the
PrintStream
class and the
format() static
method of the
String
class
are convenience methods. These convenience methods exist to make the job of text formatting easier. However,
the
Formatter
class does the real work. Let's discuss the
Formatter
class in detail. You will use these convenience
methods in the examples.
A
Formatter
is used to format text. The formatted text can be written to the following destinations:
An
•
Appendable
(e.g.
StringBuffer
,
StringBuilder
,
Writer
, etc.)
•
A
File
An
•
OutputStream
PrintStream
The following snippet of code accomplishes the same thing as the code in Listing 13-5. This time, you use a
Formatter
object to format the data. When you call the
format()
method of the
Formatter
object, the formatted text
is stored in the
StringBuilder
object, which you pass to the constructor of the
Formatter
object. When you are done
with formatting all text, you call the
toString()
method of the
StringBuilder
to get the entire formatted text.
•
A