Search code examples
javastatic-initializer

Java: what is static{}?


Can someone explain me what the following is?

public class Stuff
{
    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch ( ClassNotFoundException exception )
        {
            log.error( "ClassNotFoundException " + exception.getMessage( ) );
        }
...
}

What does this static { ...} do?

I know about static variables from C++, but is that a static block or something?

When is this stuff going to get executed?


Solution

  • The static block is called a class static initializer - it gets run the first time the class is loaded (and it's the only time it's run [footnote]).

    The purpose of that particular block is to check if the MySQL driver is on the classpath (and throw/log error if it's not).


    [footnote] The static block run once per classloader that loads the class (so if you had multiple class loaders that are distinct from each other (e.g. doesn't delegate for example), it will be executed once each.