Search code examples
javajvmjava-native-interfaceprintstream

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.


Solution

  • 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.