Strange variable "out", System.out.println ()

Below is the code from the java.lang.System class (JDK version 1.6)

public final static PrintStream out = nullPrintStream(); //out is set to 'null' private static PrintStream nullPrintStream() throws NullPointerException { if (currentTimeMillis() > 0) { return null; } throw new NullPointerException(); } 

when we write System.out.println("Something"); in our code, why don't we get a NullPointerException, even if the "out" parameter is set to "null"

In any case, out will be set using the following setOut method in the System class

 public static void setOut(PrintStream out) { checkIO(); setOut0(out); } 

Theyn why does JLS need a nullPrintStream method?

+6
source share
3 answers

Take a look at private static void initializeSystemClass() - this method is called to run, it calls setOut0() , which is native . This binds the Stream where it should be.

So, although the field may look like a public static final , it's actually not, the native code changes it.

EDIT

OP asks. Then why does JLS need the nullPrintStream method?

This is due to the java compiler - it will be "inline" static final if at the time of compilation they are assigned something constant, for example null . The compiler will actually replace each link to the field with a constant.

This will break the initialization, since objects will no longer contain a reference to Stream , but to null . Assigning a thread to return a method prevents nesting.

Some may call it a dirty hack. Wrong to use Bismarck "JDK is like sausage, it’s better not to see how it is done."

+8
source

This is how the System.out class is initialized.

There is also a method:

  private static native void setOut0(PrintStream out); 

Called in the following way:

 private static void initializeSystemClass() { 
+2
source

System.in, out and err are managed by the JVM from native code. All this magic with nullPrintStream () was there to prevent javac from inserting these fields. Since java 7 looks like

 public final static PrintStream out = null; 
+2
source

All Articles