Java Reference
In-Depth Information
[Java-API]
. In practice,
write(int)
is the
only
output method that does not flush a
PrintStream
on which automatic flushing is enabled.
Curiously, if the program is modified to use
print(char)
instead of
write(int)
, it flushes
System.out
and prints
Hello world
. This behavior contradicts the documentation for
print(char)
, which says
[Java-API]
:
Print a character. The character is translated into one or more bytes according to the platform's
default character encoding, and these bytes are written in exactly the manner of the
write(int)
method.
Similarly, if the program is modified to use
print(String)
, it flushes the stream even though the
documentation prohibits it. The documentation should almost certainly be changed to describe the
actual behavior; it would be too destabilizing to change the behavior.
The simplest change that fixes the program is to add a
System.out.flush
invocation after the loop.
If this change is made, the program prints
Hello world
as expected. It would, however, be far
better to rewrite the program to use the more familiar
System.out.println
idiom for producing
output on the console.
The lesson of this program is, as in
Puzzle 23
:
Use familiar idioms whenever possible; if you must
stray from familiar APIs, be sure to consult the documentation.
There are three lessons for API
designers: Make the behavior of your methods clear from their names, document this behavior
clearly, and correctly implement the documented behavior.
< Day Day Up >
Search WWH ::
Custom Search