When a java class get loaded first all the static fields will be loaded with their default values.
Then static inits of the class begins in order, which means static fields will be initialized as given in order.
- So in the given example code line 1 will load the class LakmaliClass with all its static fields assigning to default values.
- Then static inits will begin executing line 5, 6 and 7.
- Then instance inits will begin executing line 2, 3 and 4.
- Line 2 will load the class Second with all the static fields default values (Here no static fields)
- Then object will be created with passed values.
- Line 3 will also do the same.
class Initializer{
public static void main(String args[]){
LakmaliClass o=new LakmaliClass(); // line 1
}
}
class LakmaliClass{
{
System.out.println("Lakmali class instance init"); //line 2
Second s1=new Second(s); //line 3
Second s2=new Second(number1); //line4
}
static String text1="text1"; //line 5
static int number1=1; //line 6
static{
System.out.println("Lakmali class static init"); //line 7
}
}
class Second{
Second(String s){
System.out.println(s);
}
Second(int i){
System.out.println(i);
}
}
result:
Lakmali class static init
Lakmali class instance init
text1
1
Let's see a different example, where instance will be created in static init.
class Initializer{
public static void main(String args[]){
LakmaliClass.getInstance(); // line 1
}
}
class LakmaliClass{
{
System.out.println("Lakmali class instance init"); //line 2
Second s=new Second(text1,number1); //line3
}
static LakmaliClass o=new LakmaliClass(); //line 4
static String text1="text1"; //line 5
static int number1=1; //line 6
static{
System.out.println("Lakmali class static init"); //line 7
}
static LakmaliClass getInstance(){
return o;
}
}
class Second{
Second(String s, int i){
System.out.println("value1: "+s+"\nvalue2: "+i);
}
}
result:
Lakmali class instance init
value1: null
value2: 0
Lakmali class static init
Here you can see that instance inits had run before static init. It happend in this order.
- line 1 load class LakmaliClass with all its static fields default values.
- Static inits begin.
- First line 4 runs. It creates an instance of LakmaliClass. So instance init of LakmaliClass will be executed with current values. So text1 or number1 fields are not initialized to given values as line 5 and 6 have not executed yet. So text1 and number1 will have their default values.
- Now line 5, line 6 and line 7 will execute in order.
- Then getInstance method will be invoked.