Search code examples
javastatic-initializer

Use of static init block


I know how a static init block works.
Can anyone please tell me some typical uses of it.


Solution

  • When you want to initialize one or more static variables in one place

    It is useful, because you can apply exception handling, which is not possible with the in-line initialization.

    For example:

    public static ImageIcon defaultIcon = ImageIO.read(..);
    

    can be initialized with

    public static ImageIcon defaultIcon;
    static {
       try {
           defaultIcon = ImageIO.read(..);
       } catch (IOException ex){
         System.out.println("No default icon available");
       }
    }
    

    Another application is complex initialization. For example, if an item requires more than one line of code to be initialized. Let's say you have a configuration:

    public static Configuration configuration;
    static {
         confuguration = new Configuration();
         configuration.setSomething(..);
         configuration.setSomethingElse(..);
         ...
    }
    

    A third usage is to initialize some external API infrastructure. One example from my current project:

    static {
        org.apache.xml.security.Init.init();
    }
    

    But, as Mykola Golubyev noted, static initialization blocks make code less readable, so use them with caution. static methods do the same thing more transparently.