4

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,

  • `class PrintStream is not static to prevent the instantiation of the object.` Java does not have this concept of static classes. Why would you want to prevent the instantiation of a `PrintStream`? – Thomas Jungblut Sep 16 '18 at 12:30
  • by declaring Printstream as static in the System class this means that there is no object Printstream that will be instantiated okay you are right but what about the function println it is not static ? – Patrick Schmidt Sep 16 '18 at 12:32

1 Answers1

5

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.

curlyBraces
  • 1,095
  • 8
  • 12
  • okay based on your comment the out is not null okay now the part of calling a method non static which is println ? – Patrick Schmidt Sep 16 '18 at 12:42
  • Well, `System` has a static field of type `PrintStream`. To access it, you call `System.out`. But `PrintStream` is still a normal java class that can have non static methods. So once you got hold of the object of `PrintStream` by calling `System.out`, you can simply call any of its non-static method as `System.out.println()`. – curlyBraces Sep 16 '18 at 12:45
  • Thanks CurlyBraces this explains everything. I thought that it can only be called if the method is declared as static but this can be happen directly by static class declaration. – Patrick Schmidt Sep 16 '18 at 12:48