Reputation: 11
how come System.out.println() method prints character on the screen when out is of type print stream which is used to display bytes
Upvotes: 1
Views: 1057
Reputation: 735
PrintStream
is a byte stream and PrintWriter
is a character stream, but at the lowest level everything is byte oriented, I have read somewhere that each PrintStream
incorporates an OutputStreamWriter
, and it passes all characters through this writer to produce bytes for output.
Upvotes: 0
Reputation: 1108672
PrintStream
was introduced in Java 1.0 and used in among others System.out
. Later they realized that it was a major mistake to use platform default encoding to convert bytes to characters, so they introduced PrintWriter
later with Java 1.1 which is able to accept an OutputStreamWriter
wherein you can specify the character encoding. It was however too late then to change System.out
.
Upvotes: 11
Reputation: 597046
I guess this piece of code (from java.lang.System
) explains it:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
It is creating a FileOutputStream
to the standard out, and then wraps it in a PrintStream
. FileDescriptor.out
is "a handle to the standard output stream".
And it is converting bytes to characters using the platform default encoding.
Upvotes: 3