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 ?
System.out is initialized to
nullwhen the class is instantiated. This is set by thenullPrintStream()method inSystem.java, which just returnsnull.When the JVM has initialized, it calls the
initializeSystemClass()method. This method calls thenativemethodsetOut0()which sets theoutvariable to the appropriate value.This may seem weird but it is a necessary operation for the following reasons:
outcannot be set statically to the value becauseSystemneeds to be one of the first loaded classes (beforePrintStream).outmust befinalso that its value cannot be directly overridden by a user.outcannot be set statically, and is final, we must override the semantics of the language using anativemethod,setOut0().I hope that helps your understanding.