-4

I recently came across the following bit of java syntax:

static {
... 
}

apparently this is known as a "static initializer" (see Static Block in Java) and is "executed when the class is loaded". When should a static initializer be used? What are its advantages and disadvantages compared to just initializing variables in the usual way?

Community
  • 1
  • 1
tSchema
  • 161
  • 2
  • 9
  • Related? http://stackoverflow.com/questions/804589/use-of-initializers-vs-constructors-in-java?rq=1 – Kevin Aug 07 '13 at 20:03
  • http://www.jusfortechies.com/java/core-java/static-blocks.php – zod Aug 07 '13 at 20:03
  • when you want to initialise a static variable with code. This is the usual way of initialising variables which are not assigned to a simple expression. When you have to do this, there is no good alternative so the alternatives don't matter too much. You could create a static method to call for each variable but this is not elegant and can be more confusing. – Peter Lawrey Aug 07 '13 at 20:08

1 Answers1

1

As mentioned in comments and linked posts, it is useful when static initialization requires logic that is beyond simply assigning values to static fields, e.g.:

public class MediocreExample {

    static List<String> strings = new ArrayList<String>();

    static {
        strings.add("first");
        strings.add("second");
    }

}        

There are alternatives that do not use the initialization block:

public class MediocreExample {

    static List<String> strings = createInitialList();

    private static List<String> createInitialList () {
        List<String> a = new ArrayList<String>();
        a.add("first");
        a.add("second");
        return a;
    }

}

There isn't really a compelling reason to use the non-initializer alternative -- as you can see the initializer version is very clear and succinct -- but I'm including it to illustrate a point: Don't make design decisions blindly, know why you're choosing the option you are choosing.

Sometimes there are no convenient alternatives like that, e.g. if the goal is to print something to the console on static initialization:

public class MediocreExample {

    static {
        System.out.println("MediocreExample static init."); 
    }    

}

There are other ways to generate equivalent code but that is the cleanest.

But as usual, use the way that is most appropriate and provides the clearest and most easily maintainable code. A language is a way to express an idea, speak (type) clearly.

Jason C
  • 34,234
  • 12
  • 103
  • 151