Java Reference
In-Depth Information
The
Formatter
Class
The
Formatter
class is an interpreter for the format strings used in
format/printf
methods. The class is similar to the
PrintWriter
class except that
Formatter
defi nes
only the
format
methods and not the
printf
methods. You invoke
format
in the way
you do
PrintWriter
: passing in a format specifi er followed by a comma-separated list of
arguments.
For example, the following statements create a
Formatter
object and format a string of
primitive types. Study the code and see if you can determine its output:
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
double d = 0.1/0.3;
int x = 123;
fmt.format(“d=%5.3f and x=%6d”, d, x);
System.out.println(sb.toString());
In this example, the
Formatter
writes its output to a
StringBuilder
object. The
double d
is formatted with a width of
5
and precision of
3
. The
int x
is formatted with a width of
6
,
and the resulting
StringBuffer
looks like this:
d=0.333 and x= 123
As you can see, working with
Formatter
is similar to working with
PrintWriter
.
The
Console
Class
The
java.io.Console
class represents the JVM's console, typically the command prompt
where the Java application is executed from. The
System.in
and
System.out
objects also
represent the console, but they are byte streams. The
Console
class, new to the language as
of Java 6.0, represents a single
Console
object in your JVM that provides access to the con-
sole input and output as character streams.
The
Console
class is unique in that it does not have any constructors. There is only one
instance of this class, obtained by invoking the
static
method
System.console()
. This
method returns
null
if no console device is available in your environment.
The
Console
class contains similar
format
and
printf
methods as the
PrintWriter
class:
public Console format(String fmt, Object... args)
public Console printf(String fmt, Object... args)
As with
PrintWriter
, these two methods in
Console
are synonyms and behave in the
same manner. Let's look at an example. See if you can determine the format of the output
of the following code:
Search WWH ::
Custom Search