Sachin Kumar
Sachin Kumar

Reputation: 781

How java actually prints on screen

I'm new to java and learning java from official java documentation from oracle. In most of the program example provided by java documentation, system.out.println(...) statement is used to print the text or message on the screen. There are also some other method like print(), printf() etc for writing on screen.

I want to know how actually these methods works. I take a look on source of these methods and going into deep, I found that finally write(char cbuf[], int off, int len) method is called in every print method (directly or indirectly), and this method is abstract.

So how JVM print/write something on screen. According to me, it is internal working of JVM . JVM search for a display window and call system commands of OS, for example echo in linux and windows OS.

Am I right, if not then explain the working of these methods and correct me.

Upvotes: 3

Views: 131

Answers (1)

jdphenix
jdphenix

Reputation: 15425

Taking a look at the source for OpenJDK, there is a method at java.lang.System:254 that appears to set the System.out PrintStream value, which is called later at java.lang.System:1144.

 254:  private static native void  [More ...] setOut0(PrintStream out);

1144:  setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));

fdOut is a reference to a FileOutputStream set at java.lang.System:1141,

1141:  FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);

And the FileDescriptor.out is

handle to the standard output stream. Usually, this file descriptor is not used directly, but rather via the output stream known as System.out.

So how does a PrintStream handle methods like print()? (You probably see where I'm going to go here.

At java.io.PrintStream:582-584 is the print(char c) method,

 582:  public void print(char c) {
 583:      write(String.valueOf(c));
 584:  }

write() in turn writes the value passed and flushes the output stream passed to PrintStream().

The remaining bits of implementation are native methods, which by definition vary based upon the platform and invocation of the program. They could be anything from the console screen to a printer, or an orbital laser burning the output onto the Earth's surface.

Humor aside, I hope that helps in understanding.

Upvotes: 3

Related Questions