1

I recently fumbled into this code:

  public static ArrayList<HelloGreeting> greetings = new ArrayList<HelloGreeting>();

  static {
    greetings.add(new HelloGreeting("hello world!"));
    greetings.add(new HelloGreeting("goodbye world!"));
  }

The question is why we use static here, can't we do just this:

  public static ArrayList<HelloGreeting> greetings = new ArrayList<HelloGreeting>();

    greetings.add(new HelloGreeting("hello world!"));
    greetings.add(new HelloGreeting("goodbye world!"));

What benefit we get, space or time?

CodeYogi
  • 1,352
  • 1
  • 18
  • 41

1 Answers1

2

If you want to initialize some data after the class is loaded, when it is being initialized, then you can use static blocks. static blocks are run once per class initialization (multiple times if a class is loaded and initialized by different class loaders multiple times).

Difference between static blocks and non-static blocks (your second case should be nclosed within {..}) is that non-static blocks will execute for each instance of YourClass i.e, when new instance is being constructed. Next, static blocks are thread-safe (although a class can be loaded / initialized by multiple threads)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104