Reputation: 73
I have just downloaded the source code of jdk and I was interested in the function System.out.println
By looking to the class System in java.lang I go this part:
public final class System {
public final static PrintStream out = null;
and in java.io the class PrintStream is like this declared:
public class PrintStream extends FilterOutputStream
implements Appendable, Closeable {
public void println() {
so if we call the function in the main function System.out.println()
how can this happen if the out object is null. Why there is no java.lang.NullPointerException. Moreover, the class PrintStream is not static to prevent the instantiation of the object.
I am really a beginner in java so please enlight me with the parts I am missing here
Thanks,
Upvotes: 4
Views: 264
Reputation: 1105
System
class has a static block that calls registerNatives
method, which is a native method. There's following comment in the source code:
VM will invoke the initializeSystemClass method to complete the initialization for this class separated from clinit. Note that to use properties set by the VM, see the constraints described in the initializeSystemClass method.
So when registerNatives
is invoked from the static block, the initializeSystemClass
method mentioned in the above comment is called by the JVM. This method has initialization for out
field.
A static block is called during the class loading time. So you can be sure that whenever you call System.out.println
from your code, this static block has already been called and the out
field already initialised.
Upvotes: 5