Java will first initialize the static variables to default values (null, 0, and equivalent). This is done regardless of whether a initial value is specified or not.
It will then run all static blocks of code (not static method!), from the beginning to the bottom of the class. Initialization is also considered block of code, and it is run in the order as specified in file. Therefore, such code:
// static block of code in front
static Type variable = initialValue;
// static block of code in-between
static OtherType anotherVariable = someInitialValue;
// static block of code below
Is roughly equivalent to (roughly - since they are not syntactically equivalent)
static Type variable;
static OtherType anotherVariable;
// static block of code in front
static {
variable = initialValue;
}
// static block of code in-between
static {
anotherVariable = someInitialValue;
}
// static block of code below
(Just before any call to the constructor, all non-static blocks of code will be run before the constructor is called. It is not very relevant to the OP's piece of code, though.)
From the scheme above, Foo() constructor will be called. And count1 and count2 will be initialized to 1.
After executing the singleton = new Foo() initializer, it will go on to execute the initialization count2 = 0, and effectively set count2 to 0.
At this point, we will enter the main() function, and print out. If the constructor is called the second time, as mentioned above, non-static blocks of code will be run before the constructor, and the constructor will be called again to increment value of count1 and count2 each by 1. Nothing strange happens at this step.
You can try compile and run this piece of code to see the effect:
class Foo {
static {
System.out.println("static 0: " + Foo.sigleton + " " + Foo.sigleton.count1 + " " + Foo.sigleton.count2);
}
private static Foo sigleton=new Foo();
static {
System.out.println("static 1: " + sigleton + " " + sigleton.count1 + " " + sigleton.count2);
}
private static int count1;
static {
System.out.println("static 2: " + sigleton + " " + sigleton.count1 + " " + sigleton.count2);
}
private static int count2=0;
static {
System.out.println("static 3: " + sigleton + " " + count1 + " " + count2);
}
{
System.out.println("non-static 1: " + sigleton + " " + count1 + " " + count2);
}
private Foo (){
count1++;
count2++;
System.out.println(count1 + " " + count2);
}
{
System.out.println("non-static 2: " + sigleton + " " + count1 + " " + count2);
}
public static Foo getInstance(){
return sigleton;
}
public static void main(String[] args) {
Foo f= Foo.getInstance(); // case 1
System.out.println(f.count1);
System.out.println(f.count2);
Foo t= new Foo(); // case 2
System.out.println(t.count1);
System.out.println(t.count2);
}
}
sigletonissingleton.