Java Reference
In-Depth Information
tem.out.println() is of type PrintStream . This class outputs data of any of the basic types as a string.
For example, an int value of 12345 becomes the string "12345" as generated by the valueOf() method
from the String class. However, you also have the PrintWriter class that I discussed earlier in the chapter
to do the same thing because this class has all the methods that PrintStream provides.
The principle difference between the two classes is that with the PrintWriter class you can control
whether or not the stream buffer is flushed when the println() method is called, whereas with the
PrintStream class you cannot. The PrintWriter class flushes the stream buffer only when one of the
println() methods is called, if automatic flushing is enabled. A PrintStream object flushes the stream
buffer whenever a newline character is written to the stream, regardless of whether it was written by a
print() or a println() method.
Both the PrintWriter and PrintStream classes format basic data as characters. In addition to the
print() and println() methods that do this, they also define the printf() method mentioned in Chapter
6. This method gives you a great deal more control over the format of the output and also accepts an arbit-
rary number of arguments to be formatted and displayed.
The printf() Method
The printf() method that is defined in the PrintStream and PrintWriter classes produces formatted out-
put for an arbitrary sequence of values of various types, where the formatting is specified by the first argu-
ment to the method. System.out happens to be of type PrintStream , so you can use printf() to produce
formatted output to the command line. The PrintStream and PrintWriter classes define two versions of
the printf() method, shown in Table 8-9 .
TABLE 8-9 : printf() Method Versions
VERSION
DESCRIPTION
Outputs the values of the elements in args according to format specifications in format . An excep-
tion of type NullPointerException is thrown if format is null .
printf(String
format,
Object ...
args)
This version works as the preceding version does except that the output is tailored to the locale speci-
fied by the first argument. I explain how you define objects of the java.util.Locale class type a
little later in this chapter.
printf(Locale
loc,
String
format,
Object ...
args)
The format parameter is a string that should contain at least one format specification for each of the ar-
gument values that follow the format argument. The format specification for an argument value just defines
how the data is to be presented and is of the following general form:
%[argument_index$][flags][width][.precision]conversion
The square brackets around components of the format specification indicate that they are optional, so the
minimum format specification if you omit all of the optional parts is %conversion .
 
 
Search WWH ::




Custom Search