When to use initializers?

188 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.