This question already has an answer here:
One of my friends asked me that which will load first static variable or static block.
My answer points to static variable.
So he gave me two equations and said to differentiate between them
First Equation
public class Some {
public static void main(String args[])
{
System.out.println(Some.x);
}
static {
System.out.println(Some.x);
}
static int x=90;
}
O/P: 0 90
Second Equation
public class Some {
public static void main(String args[])
{
System.out.println(Some.x);
}
static int x=90;
static {
System.out.println(Some.x);
}
}
O/P: 90 90
I tried to decompile the byte code and found it's same for both the above equation. Please help me to differentiate between them. I am confused when the static variable will initialised.
Static blocks are initialised in the order they appear in the source file. There are several questions relating to this on stack overflow already... This one has a good answer for you: Java : in what order are static final fields initialized?
static variables and static blocks are executed in an order in which they appear.
Here first O/P: 0 90 as in the
System.out.println(Some.x);
statement of the static block executed after the static variable initialization statementstatic int x=90;
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.
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.
I am giving a simple example for control flow of static and instance stuffs:
Suppose you have 2 clases A and B. class A extends to class B. and class B has a main method. After successful compilation of both your command on cmd is like:
Now what will happen see step by step:
the constructor of class A(default constructor or any other if you called it from B's constructor) will be executed
then all instance members initialization and instance block execution will be done in class B
Note: static members and blocks execution is done only one time while loading class for first time, while instance members and instance blocks are executed each time as we create an object of the class. Please let me know if I am not correct.