Is System.out declared as static final and initialized to zero?
As I passed through System.class
, I found what seemed strange to me. When you look at the ad System.in, System.out, System.err
, they are decalized as final static
, but also initialized withnull
public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;
Since they final
can only be initialized once, how do they become manageable?
When do we use System.out.print("...");
Obviously what is out
not null
, how is it not null
?
So can anyone please explain that out is initialized, which is already declared final?
source to share
Initialized with native code in a static initializer. At the top of System.java, you have:
/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
registerNatives();
}
The method registerNatives()
will initialize in / out / err - and it does it in native code - native code can pretty much do whatever it wants and is not constrained by all the java language rules. (Though you can get around setting up an already initialized final field in Java via reflection too)
source to share
Since endings can only be initialized once, how are they managed?
While you can modify the variable static final
using reflection, in this case the fields are modified using native methods.
From java.lang.System
public static void setIn(InputStream in) {
checkIO();
setIn0(in);
}
// same for setOut(), setErr()
private static native void setIn0(InputStream in);
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);
When we use System.out.print ("..."); Obviously out is not null but is final static, how is it not null?
It gets installed before you can use it.
You may wonder why this is so? The answer almost certainly has to do with loading the order classes. Many of the classes are started in order, but they need to be initialized in an order that works.
So can anyone please explain that out is initialized, which is already declared final?
This is because it is final
not as final as you think. It has been suggested what we need final final
.
source to share