Why is PrintStream "out" and InputStream "in" null?

Out of curiosity, I looked at the source code for some Java API classes found at docjar.com . I saw the java.lang.System class and saw that PrintStream "out" (that is, System.out) has the following code:

public final static PrintStream out = null; 

and in the comments:

 The "standard" output stream. This stream is already open and ready to accept output data. 

My assignment: I know that final variables cannot be changed, so why is this so when declared? Why doesn't Java throw a NullPointerException when calling a method for "out"? The same goes for System.in.

Thanks for any clarification.

+6
source share
2 answers

There is a native java.lang.System # registerNatives () method here. If you look at it in jvm source code, it will assign sysin, sysout and syserr from native code. Before java 7, these declarations looked like public final static InputStream in = nullInputStream(); but I suppose they changed it so that it was just null with some hacks in javac and not just embed it.

+1
source
  • Look at private static void initializeSystemClass () - this method is called to run, it calls setOut0 (), which is the native method. This connects the stream where it should be.

    Thus, although the field may look like a public static final, it really is not, the native code changes it.

    The JVM calls the private static void initializeSystemClass () method, which initializes it.

0
source

Source: https://habr.com/ru/post/955230/


All Articles