TheRenegade
TheRenegade

Reputation: 137

In Java, how does PrintStream end up printing text to the console?

So from my understanding, the PrintStream must use some sort of Java Native Interfacing to communicate with the Operating System so it can write to the standard output, or does java use some other technique? I would like to know as the JVM's architectures intrigues me. It is very interesting to me understand the way it works and the architecture of the system itself.

Upvotes: 0

Views: 287

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100169

Standard output stream in OpenJDK is a PrintStream which wraps BufferedOutputStream, which wraps FileOutputStream which is created from FileDescriptor. There are special FileDescriptor objects which correspond to the stdin, stdout and stderr (in particular, see FileDescriptor.out). They have well known numbers (for example, stdout file descriptor is 1). So the real logic is inside the FileOutputStream.writeBytes method which is of course native. On the Java side we have buffering, synchronization and translation of characters into bytes. The low-level stuff (writing bytes directly to the file descriptor) is done by native code.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

The Java System.out PrintStream writes to stdout. Wikipedia describes stdout as,

The file descriptor for standard output is 1 (one); the POSIX <unistd.h> definition is STDOUT_FILENO; the corresponding <stdio.h> variable is FILE* stdout; similarly, the <iostream> variable is std::cout.

While the Javadoc for System.out says (in part)

The "standard" output stream. This stream is already open and ready to accept output data.

Upvotes: 0

Related Questions