Static block are executed when classes are loaded where as normal blocks are executed when an instance of the class enclosing the block is created.
Just for the record prior to java 7 static blocks were executed before main() method was searched in the project. But from java 7 main() is first looked up. So you will get an error if you don't have main.So saying I know the static blocks run before main
is a bit ambiguous. main() method is looked up prior to executing static blocks but the main execution will start after the static blocks are handled.
Also non static blocks are executed before the corresponding constructor is invoked.
For example
public class Tester {
{
System.out.println("In some random block");
}
static {
System.out.println("In static block");
}
public Tester() {
System.out.println("Constructor");
}
public static void main(String args[]) {
Tester t = new Tester();
}
}
will print
In static block
In some random block
Constructor