Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the PrintStream "out" and InputStream "in" null? [duplicate]

Tags:

java

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.

like image 611
djmordigal Avatar asked Oct 04 '13 05:10

djmordigal


1 Answers

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.

like image 120
Denis Tulskiy Avatar answered Oct 22 '22 16:10

Denis Tulskiy