Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.in declared as nullInputStream() instead of null?

Tags:

java

In the System class, in, out, and err are static fields. These fields are declared for example:

 public final static InputStream in = nullInputStream();

Why declare nullInputStream() instead of null?

like image 551
user1357722 Avatar asked May 27 '12 13:05

user1357722


1 Answers

The source code has the following comment:

/**
 * The following two methods exist because in, out, and err must be
 * initialized to null.  The compiler, however, cannot be permitted to
 * inline access to them, since they are later set to more sensible values
 * by initializeSystemClass().
 */

In short, since System.in is a static final variable, if it was set to null, the compiler would consider it as a constant, and would replace all the references to System.in in other classes with null (that's what inlining means). Which would obviously make everything non-functional. Some native code must be used to replace the value of this System.in final value (which normally should never change) once the system is initialized.

To resume: it's used to avoid a compiler optimization that should not be made in this very particular case, because System.in is a final field that can change, which is normally impossible.

like image 70
JB Nizet Avatar answered Oct 06 '22 00:10

JB Nizet