Hi All,
My knowledge on static(variable, method, block) behaviour is this:
1> static blocks of all the super class till the sub class gets called when, the sub class is loaded
2> A class gets loaded, when its instantiated or its static variable is used or its static method is called.
3> In a class the order of execution of static variable, static block and static method takes place in textual order, as a single block example:
StaticBlock=0
Main=10
Now, when I was digging more into the behaviour of "static", I came to know some strange statements on the internet. One of them is
"1>static Variables are executed when the JVM loads the Class, and the Class gets loaded when either its been instantiated or its static method is being called.
2>static Initializer Block gets Initialized before the Class gets instantiated or before its static method is called, and Even before its static variable is used."
Here, I agree with point 1, but what does 2nd point mean? How can I achive this? initialization of static block
before Class gets instantiated or before its static method is called, and Even before its static variable is used!!!
Some of them also said: static variables are initialised before the static block, I tried the above program which proves it wrong. Am I wrong? Is my understanding about static is totally wrong?
Also, I got this code on the internet:
My output is
static null
1> Here I cant understand why is
String, static variable gets its value, when it has been declared after the initialization block?
2> Why is the same mechanism, whatever that works with String is not working with Integer?
3> I noticed that the mechanism works with primitive as well, and both in case of primitive and String if final keyword is removed, then the values printed will be default i.e null for String and 0 for int primitive.
4> They talk about "Constant folding" in the discussion, at this point I am totally lost
Please help,
Regards,
Prathiima