As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.
But I do not understand why we ne
You first need to understand that your application classes themselves are instantiated to java.class.Class
objects during runtime. This is when your static blocks are ran. So you can actually do this:
public class Main {
private static int myInt;
static {
myInt = 1;
System.out.println("myInt is 1");
}
// needed only to run this class
public static void main(String[] args) {
}
}
and it would print "myInt is 1" to console. Note that I haven't instantiated any class.