6

Out of curiosity I was looking through the source code for some of the Java API classes found at docjar.com. I saw the java.lang.System class and saw that the PrintStream "out" (i.e., System.out) had the following code:

public final static PrintStream out = null;

and in the comments it says:

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

My queston is, I know final variables can't be modified, so why is it null when declared? Why doesn't Java throw a NullPointerException when a method for "out" is called? The same goes for System.in as well.

Thanks for any clarification.

djmordigal
  • 549
  • 1
  • 5
  • 16

2 Answers2

1

There's a java.lang.System#registerNatives() native method. If you look at it in jvm source code, it assigns sysin, sysout, and syserr from native code. Before java 7 these declarations looked like public final static InputStream in = nullInputStream(); but I guess they changed it to be just null with some hacks in javac not to just inline it.

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68
0
  • Take a look at the private static void initializeSystemClass() - this method is called to start things up, it calls setOut0() which is a native method. This ties the Stream into where it's supposed to be.

    So even though the field may look public static final it actually isn't, the native code changes it.

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

Shyam
  • 6,376
  • 1
  • 24
  • 38