One example of a time when you'd use (and I have used) static initialization blocks is to initialize a collection of elements. For example, if I have some set of parsers that are stored in a static map:
private static Map<String, Parser> parsers = new HashMap<String, Parser>();
I may use a static initialization block to populate the members of this map:
static {
parsers.put("node", new NodeParser());
parsers.put("tree", new TreeParser());
parsers.put("leaf", new LeafParser());
//etc.
}
I would do this because I want the map to be static rather than part of a particular object, or if I only want there to be one of these maps (maybe I only need one).
The difference between this and a constructor is the constructor is called at object instantiation whereas the static initialization block will be called when the class is loaded.
That is, if you call
MyClass.parsers.get("node");
The MyClass
constructor is never called so if you waited to initialize the parsers
map until the constructor, the above call would return null.