out in System.out.println()

srk picture srk · Feb 26, 2012 · Viewed 13.5k times · Source

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey. I was asked in an interview to elucidate System.out.println(); I explained the following way

//this class belongs to java.lang package
class System{
  public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
 public void println..
}

I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as

System.out.pritnln(); 

he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null

my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.

Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?

Answer

Jivings picture Jivings · Feb 26, 2012

System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.

When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.

This may seem weird but it is a necessary operation for the following reasons:

  • out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
  • out must be final so that its value cannot be directly overridden by a user.
  • Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().

I hope that helps your understanding.