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?