I want to add that static variables and static initializers are executed in order of appearance at the time of class loading. So, if your static initializer relies on some static variable, it must be initialized before the particular static block, e.g.
final static String JDBC_DRIVER = getJdbcDriver( );
static
{
try
{
Class.forName(JDBC_DRIVER);
}
catch ( ClassNotFoundException exception )
{
log.error( "ClassNotFoundException " + exception.getMessage( ) );
}
}
In this example getJdbcDriver
will get executed before static initializer. Also, there may be more than 1 static initializer in the class. Once again they are executed in order of appearance.
I also want to mention the existence of instance initializers here, as they do come as surprise when seen for the first time. They look like a code block inside the class body, like this.
class MyClass
{
final int intVar;
{
intVar = 1;
}
}
In general case their use is somewhat unnecessary, because of the constructor, but they are useful in implementing Java's version of closures.