Reputation: 7658
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
?
Upvotes: 10
Views: 1061
Reputation: 691765
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.
Upvotes: 10
Reputation: 6657
You are wrong.
In Java source code it is written as
public final static InputStream in = null;
not
public final static InputStream in = nullInputStream();
You can take reference of the source code for the System
class here.
Upvotes: -1