Java Reference
In-Depth Information
e.printStackTrace();
}
}
}
The PrintStream class is another interesting example that implements extra methods to allow for
easy output formatting on top of a normal byte output stream:
void print(String s) : Writes the specified string to this print stream. Note that this
method is overridden to also accept other primitive types (char, double, etc.).
void println(String s) : Writes the specified string to this print stream, but also termi-
nates the line (i.e. starts a new line). Note that this method is overridden to also accept other
primitive types (char, double, etc.).
void format(String format, Object... args) : This function takes a “format string”
as its first argument and the variables you want to format as the following arguments. The
format string contains a number of percentage (%) fields representing where, which, and how
variables should be formatted. The most basic conversions are:
%d: to format an integer value as a decimal value
%f: to format a floating-point value as a decimal value
%n: to output a line terminator
%x: to format an integer value as a hexadecimal value (less useful)
%s: to format any value as a string (effectively calling the toString method)
%%: to output a percentage sign
Note that the System.out object we've been using to send output to the console is in fact an
example of a PrintStream . It is opened at the start of your program and closed automatically at the
end, so you can use it directly without further management. The following Try It Out shows some
examples of PrintStream 's methods.
Formatting Output with printStream
try it out
This Try It Out shows some examples of formatting output with a PrintStream byte stream.
1.
Create a new project in Eclipse if you haven't done so already.
2.
Create the following class and execute it to see the examples in action:
public class FormattingOutput {
public static void main(String[] args) {
/* System.out is a PrintStream, but a PrintStream class
is a specialization of an OutputStream. The write() method
is thus available: */
System.out.write(50); // 50 corresponds to '2'
System.out.write((int)'\n'); // newline
Search WWH ::




Custom Search