This is the source code for demonstrating a static block and static method.
class StaticDemo
{
static int count=10;
StaticDemo(){
count++;
}
static void display(){
System.out.println(count);
}
static{
System.out.println("Static Block written Before Main");
}
public static void main(String args[]){
StaticDemo t1=new StaticDemo();
StaticDemo t2=new StaticDemo();
StaticDemo.display();
t2.display();
}
static{
System.out.println("Static Block written After Main");
}
}
I expect an output of
Static Block written Before Main
Static Block written After Main
11
12
whereas I get an output of
Static Block written Before Main
Static Block written After Main
12
12
I understand that the static blocks are the first set of code to be executed and hence the order of the first 2 statements. However, when the JVM creates the object t1 of StaticDemo class, doesn't the value of count get incremented to 11 ( 10+1 )? When does the initialization/increment actually occur in the program? Thank you!