114

So I've been brushing up on my Java skills as of late and have found a few bits of functionality that I didn't know about previously. Static and Instance Initializers are two such techniques.

My question is when would one use an initializer instead of including the code in a constructor? I've thought of a couple obvious possibilities:

  • static/instance initializers can be used to set the value of "final" static/instance variables whereas a constructor cannot

  • static initializers can be used to set the value of any static variables in a class, which should be more efficient than having an "if (someStaticVar == null) // do stuff" block of code at the start of each constructor

Both of these cases assume that the code required to set these variables is more complex than simply "var = value", as otherwise there wouldn't seem to be any reason to use an initializer instead of simply setting the value when declaring the variable.

However, while these aren't trivial gains (especially the ability to set a final variable), it does seem that there are a rather limited number of situations in which an initializer should be used.

One can certainly use an initializer for a lot of what is done in a constructor, but I don't really see the reason to do so. Even if all constructors for a class share a large amount of code, the use of a private initialize() function seems to make more sense to me than using an initializer because it doesn't lock you into having that code run when writing a new constructor.

Am I missing something? Are there a number of other situations in which an initializer should be used? Or is it really just a rather limited tool to be used in very specific situations?

1
  • 2
    Since instance initializers are a little-known feature, here's an example to help readers: private final int somevar; {somevar = 2;} (note, no constructor.) For more fun, search "double brace initialization" (syntax hack). Sep 9, 2016 at 9:37

10 Answers 10

65

Anonymous inner classes can't have a constructor (as they're anonymous), so they're a pretty natural fit for instance initializers.

64

Static initializers are useful as cletus mentioned and I use them in the same manner. If you have a static variable that is to be initialized when the class is loaded, then a static initializer is the way to go, especially as it allows you to do a complex initialization and still have the static variable be final. This is a big win.

I find "if (someStaticVar == null) // do stuff" to be messy and error prone. If it is initialized statically and declared final, then you avoid the possibility of it being null.

However, I'm confused when you say:

static/instance initializers can be used to set the value of "final" static/instance variables whereas a constructor cannot

I assume you are saying both:

  • static initializers can be used to set the value of "final" static variables whereas a constructor cannot
  • instance initializers can be used to set the value of "final" instance variables whereas a constructor cannot

and you are correct on the first point, wrong on the second. You can, for example, do this:

class MyClass {
    private final int counter;
    public MyClass(final int counter) {
        this.counter = counter;
    }
}

Also, when a lot of code is shared between constructors, one of the best ways to handle this is to chain constructors, providing the default values. This makes is pretty clear what is being done:

class MyClass {
    private final int counter;
    public MyClass() {
        this(0);
    }
    public MyClass(final int counter) {
        this.counter = counter;
    }
}
3
  • 4
    That was what I was saying yes. I had it in my head that finals had to be set when they are declared, instead of only being able to be set once. It's a bit of a foolish idea when I think about it, but it was in my head nonetheless. Thank you for clearing that up.
    – Inertiatic
    Apr 29, 2009 at 23:37
  • I forgot to add the bit about chaining constructors, so I just added it.
    – Eddie
    Apr 29, 2009 at 23:41
  • 1
    IMHO the instance initializers are just "copied" into constructor, therefore they can do the same as constructor code, they're constructor code, albeit they are visually separated. Sep 11, 2013 at 21:53
27

I most often use static initializer blocks for setting up final static data, especially collections. For example:

public class Deck {
  private final static List<String> SUITS;

  static {
    List<String> list = new ArrayList<String>();
    list.add("Clubs");
    list.add("Spades");
    list.add("Hearts");
    list.add("Diamonds");
    SUITS = Collections.unmodifiableList(list);
  }

  ...
}

Now this example can be done with a single line of code:

private final static List<String> SUITS =
  Collections.unmodifiableList(
    Arrays.asList("Clubs", "Spades", "Hearts", "Diamonds")
  );

but the static version can be far neater, particularly when the items are non-trivial to initialize.

A naive implementation may also not create an unmodifiable list, which is a potential mistake. The above creates an immutable data structure that you can happily return from public methods and so on.

3
  • 4
    I don't quite like your specific example because it's much more suited for implementation as an enum.
    – JAB
    Jun 7, 2013 at 13:10
  • 23
    Then change SUITS to PAST_GIRLFRIENDS or sth else. But you are right, since the likelihood of the classic card set getting changed is about zero, enums would be more... suited.
    – mike
    Jul 22, 2013 at 10:29
  • Be careful about "immutable" here, actually it's read-only. The original list wrapped with Collections.unmodifiableList(...) can be modified, and then the "view" you get will change too.
    – Leo Tapia
    Dec 8, 2022 at 17:33
16

Just to add to some already excellent points here. The static initializer is thread safe. It is executed when the class is loaded, and thus makes for simpler static data initialization than using a constructor, in which you would need a synchronized block to check if the static data is initialized and then actually initialize it.

public class MyClass {

    static private Properties propTable;

    static
    {
        try 
        {
            propTable.load(new FileInputStream("/data/user.prop"));
        } 
        catch (Exception e) 
        {
            propTable.put("user", System.getProperty("user"));
            propTable.put("password", System.getProperty("password"));
        }
    }

versus

public class MyClass 
{
    public MyClass()
    {
        synchronized (MyClass.class) 
        {
            if (propTable == null)
            {
                try 
                {
                    propTable.load(new FileInputStream("/data/user.prop"));
                } 
                catch (Exception e) 
                {
                    propTable.put("user", System.getProperty("user"));
                    propTable.put("password", System.getProperty("password"));
                }
            }
        }
    }

Don't forget, you now have to synchronize at the class, not instance level. This incurs a cost for every instance constructed instead of a one time cost when the class is loaded. Plus, it's ugly ;-)

1
  • so if user.prop is created after the class has been used for the first time it will never be taken into account or is it after the compilation ? (for the static init)
    – Ced
    Jun 4, 2016 at 15:30
13

I read a whole article looking for an answer to the init order of initializers vs. their constructors. I didn't find it, so I wrote some code to check my understanding. I thought I would add this little demonstration as a comment. To test your understanding, see if you can predict the answer before reading it at the bottom.

/**
 * Demonstrate order of initialization in Java.
 * @author Daniel S. Wilkerson
 */
public class CtorOrder {
  public static void main(String[] args) {
    B a = new B();
  }
}

class A {
  A() {
    System.out.println("A ctor");
  }
}

class B extends A {

  int x = initX();

  int initX() {
    System.out.println("B initX");
    return 1;
  }

  B() {
    super();
    System.out.println("B ctor");
  }

}

Output:

java CtorOrder
A ctor
B initX
B ctor
3
  • Exactly the example I was looking for!!! Hi Daniel, thx for the ex. Just have one question: Why did "A ctor" run first? I predicted "B initX, A ctor, B ctor". Also, you seem to know the language pretty well, would you agree?
    – Cody
    Jun 27, 2013 at 6:23
  • A ctor runs first because to make a B you first have to have an A. Not sure how well I know the language, as my brain refuses to learn C++ and Java any better than it already knows them because these languages are not that well designed so the things I don't know often taste like the leftover dregs at the bottom of a glass: bitter.
    – Daniel
    Jun 27, 2013 at 17:52
  • 5
    If you extend this example by initialization blocks and static initialization blocks, it would be even more useful. Dec 2, 2014 at 11:43
8

A static initializer is the equivalent of a constructor in the static context. You will certainly see that more often than an instance initializer. Sometimes you need to run code to set up the static environment.

In general, an instance initalizer is best for anonymous inner classes. Take a look at JMock's cookbook to see an innovative way to use it to make code more readable.

Sometimes, if you have some logic which is complicated to chain across constructors (say you are subclassing and you can't call this() because you need to call super()), you could avoid duplication by doing the common stuff in the instance initalizer. Instance initalizers are so rare, though, that they are a surprising syntax to many, so I avoid them and would rather make my class concrete and not anonymous if I need the constructor behavior.

JMock is an exception, because that is how the framework is intended to be used.

6

There is one important aspect that you have to consider in your choice:

Initializer blocks are members of the class/object, while constructors are not. This is important when considering extension/subclassing:

  1. Initializers are inherited by subclasses. (Though, can be shadowed)
    This means it is basically guaranteed that subclasses are initialized as intended by the parent class.
  2. Constructors are not inherited, though. (They only call super() [i.e. no parameters] implicitly or you have to make a specific super(...) call manually.)
    This means it is possible that a implicit or exclicit super(...) call might not initialize the subclass as intended by the parent class.

Consider this example of an initializer block:

    class ParentWithInitializer {
        protected String aFieldToInitialize;

        {
            aFieldToInitialize = "init";
            System.out.println("initializing in initializer block of: " 
                + this.getClass().getSimpleName());
        }
    }

    class ChildOfParentWithInitializer extends ParentWithInitializer{
        public static void main(String... args){
            System.out.println(new ChildOfParentWithInitializer().aFieldToInitialize);
        }
    }

output:

initializing in initializer block of: ChildOfParentWithInitializer
init

-> No matter what constructors the subclass implements, the field will be initialized.

Now consider this example with constructors:

    class ParentWithConstructor {
        protected String aFieldToInitialize;

        // different constructors initialize the value differently:
        ParentWithConstructor(){
            //init a null object
            aFieldToInitialize = null;
            System.out.println("Constructor of " 
                + this.getClass().getSimpleName() + " inits to null");
        }

        ParentWithConstructor(String... params) {
            //init all fields to intended values
            aFieldToInitialize = "intended init Value";
            System.out.println("initializing in parameterized constructor of:" 
                + this.getClass().getSimpleName());
        }
    }

    class ChildOfParentWithConstructor extends ParentWithConstructor{
        public static void main (String... args){
            System.out.println(new ChildOfParentWithConstructor().aFieldToInitialize);
        }
    }

output:

Constructor of ChildOfParentWithConstructor inits to null
null

-> This will initialize the field to null by default, even though it might not be the result you wanted.

6
  • What do you mean that initializers can be shadowed? Dec 9, 2019 at 7:42
  • A sub-class might also change or initialize the parent field "aFieldToInitialize" in a static block or other means. The parent static block still will be executed, but the child might overwrite the data again.
    – Vankog
    Dec 13, 2019 at 9:54
  • aFieldToInitialize is final. It can't be overwritten. Dec 13, 2019 at 10:30
  • Touché. The point stays the same, though ;-) I removed the final for simplicity sake.
    – Vankog
    Dec 18, 2019 at 16:33
  • 2
    What you're saying still doesn't make sense. A base class should always design its constructors to initialize itself correctly, and then the problem you try to invent doesn't exist. Initializers do not have any advantages over constructors. Dec 18, 2019 at 17:46
4

I would also like to add one point along with all the above fabulous answers . When we load a driver in JDBC using Class.forName("") the the Class loading happens and the static initializer of the Driver class gets fired and the code inside it registers Driver to Driver Manager. This is one of the significant use of static code block.

3

As you mentioned, it's not useful in a lot of cases and as with any less-used syntax, you probably want to avoid it just to stop the next person looking at your code from spending the 30 seconds to pull it out of the vaults.

On the other hand, it is the only way to do a few things (I think you pretty much covered those).

Static variables themselves should be somewhat avoided anyway--not always, but if you use a lot of them, or you use a lot in one class, you might find different approaches, your future self will thank you.

0

Note that one big issue with static initializers that perform some side effects, is that they cannot be mocked in unit tests.

I've seen libraries do that, and it's a big pain.

So it's best to keep those static initializers pure only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.