Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

out in System.out.println()

Tags:

java

jvm

system

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 ?

like image 753
srk Avatar asked Feb 26 '12 16:02

srk


2 Answers

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.

like image 98
Jivings Avatar answered Oct 19 '22 22:10

Jivings


System.out is a normal static attribute, it was set by the JVM through the initializeSystemClass() method during JVM initialization. You can even change it (although it's not recommended) by simply calling System.setOut(printOutStream);, where printOutStream is the stream you want to use as standard output.

Here's a nice article detailing how does System.out.println() work.

like image 28
Óscar López Avatar answered Oct 19 '22 23:10

Óscar López