When I was going through the System.class
I found something which seemed strange to me. When you look at declaration of System.in, System.out, System.err
these are decalred as final static
but also initialized with null
public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;
Since final
can be initialized only once then how these are getting managed ?
When we use System.out.print("...");
It is obvious that out
is not null
but being a final static
how it is not null
?
So can any one explain that how out is initialized which is already declared final ?
If you do not explicitly initialize a static (or external) variable, it will have a value of zero of the appropriate type, unless it is a pointer, in which case it will be initialized to NULL .
The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
We can initialize a final static variable at the time of declaration. Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.
The final keyword implies something cannot be changed. The static keyword implies class-level scope. When you combine static final in Java, you create a variable that is global to the class and impossible to change.
It is 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 registerNatives()
method will initialize in/out/err - and it's doing so in native code - native code can pretty much do whatever it want and are not limited to all of the java language rules. (Though you could get around setting an already initialized final field in Java via reflection too)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With