Java Reference
In-Depth Information
Discussion
In certain circumstances (such as a server program with no connection back to the user's ter-
minal),
System.out
and
System.err
can become very important debugging tools (assuming
that you can find out what file the server program has redirected standard output into; see
Discussion
)
.
System.out
is a
PrintStream
connected to the “standard output”—whatever that is on your
operating system and your runtime environment—so in every introductory text you see a
System
.
out
.
println
(
"Hello World of Java"
);
The
println
method is polymorphic; it has several forms for
Object
(which obviously calls
the given object's
toString( )
method), for
String
, and for each of the primitive types
(
int
,
float
,
boolean
, etc.). Each takes only one argument, so it is common to use string
concatenation:
System
.
out
.
println
(
"The answer is "
+
myAnswer
+
" at this time."
);
Remember that string concatenation is also polymorphic: you can “add” anything at all to a
string, and the result is a string.
System.err
is a
PrintStream
connected to “the standard error output”—again, whatever
that means in your environment. In a lot of cases, it makes no difference which of the two
outputs you use. But using
System.err
sends a clear signal that the output you are convey-
ing has some importance as an indication of failure. On a dumb terminal output, these
streams will be indistinguishable. However, most IDEs will use color highlighting in the
Console view when you run an application. For example, Eclipse (see
Compiling, Running,
and Testing with an IDE
)
will show the standard output in black or blue, but the standard er-
ror stream in red; this makes it easy to find actual errors when there is a lot of nonerror out-
put.
Up to here I have been using a
Stream
,
System.out
, or
System.err
. What if you want to
use a
Writer
? The
PrintWriter
class has all the same methods as
PrintStream
and a con-
structor that takes a
Stream
, so you can just say: