This is one of most important interview question asked and probably this will be the most executed statement in Java. Many developers doesn’t know how System.out.println() actually works. In this article we will learn how it actually works.
Lets now break them into small pieces and for better understanding.
Role of Dot operator
We all know that in Java we use the Dot operator to call the methods or variable of a class. Here ‘out’ is the mysterious part as we doesn’t whether it is a variable or method ?. ‘out’ cannot possibly be a method as we don’t have a parenthesis() at the end and we are not calling like “System.out(“JIP”).println”, so from this we can be sure that out is a variable and not a method.
What type of variable is ‘out’ ?
Now we have come to a conclusion that ‘out’ is a variable, now comes the question what type of variable is ‘out’ is it static variable or instance variable ? We all know that only static variables can be called with the class name directly, same is happening here also System is a class in java.lang package we are using it to call ‘out’ variable. Moreover ‘out’ cannot be a instance variable as we not creating any instance for calling it.
In the System class, ‘out’ is declared like below
public final static PrintStream out = nullPrintStream();
out is a static final reference of the PrintStream class.
How ‘out’ is initialized ?
We may think that nullPrintStream() method initialized ‘out’ reference, but it is not the case the nullPrintStream() simply returns null or throws an NullPointerException.
private static PrintStream nullPrintStream() throws NullPointerException { if (currentTimeMillis() > 0) { return null; } throw new NullPointerException(); }
then how ‘out’ is initialized ? When the JVM is initialized, the method initializeSystemClass() is called which initializes the out variable through setOut() method.
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true))
Finally how System.out.println() method works ?
Lets put all together
-
- ‘out’ is a static final reference of the PrintStream class declared in the System class.
- ‘out’ is initialized through the setOut() method which is called inisde initializeSystemClass() method of the System class.
- Finally about println(), it is the method which is declared inside the PrintStream class
public class PrintStream extends FilterOutputStream { //out object is inherited from FilterOutputStream class public void println() { ...} }
Leave a Reply