out in System.out.println()

后端 未结 8 1035
刺人心
刺人心 2020-12-01 03:26

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

相关标签:
8条回答
  • System.out is provided by the JVM. By the time your main method is called, System.out is open and ready for use.

    See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#out

    0 讨论(0)
  • 2020-12-01 03:57

    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.

    0 讨论(0)
提交回复
热议问题