0

Why do we use static blocks when we can use static methods for initializing static variables? What difference does it make? What is the logic to this.

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
ross
  • 25
  • 1

3 Answers3

7

I assume you are referring to static initializer blocks?

static { ... }

Static initializer blocks and static methods are both required because they do different things.

Static initializer blocks are blocks for initializing the class. They are run exactly once, when the class is loaded. They don't return anything, and can't throw a checked exception because there is no way to declare throws.

In fact, a static field with an initializer:

static int a = 0;

Is actually converted to a field declaration and a static initializer block:

static int a;

static {
  a = 0;
}

You can assign zero or more static final variables in a static initializer, provided they have not already been assigned.

Static methods can be invoked at any time. They can return a value, and throw checked exceptions. You cannot assign static final variables in a static method (although you can assign non-final static variables).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

You are thinking about very 2 different ideas about initialize object. for example:

class A {
   static Map<String, String> map;

   static {
      map = new HashMap<String, String>();
   }

   public static void initializeMap() {
       map = new HashMap<String, String>();
   }

   public static void insert(String key, String value) {
       map.put(key, value);
   }
}

If we use static initializer block, the very first time you use any static method (i.e: insert), it will run static block first. And by doing this, you are safe for concurrency control. i.e: there are multiple threads try to call method insert at very beginning, Java will only run initialize block once.

Using static method for initialize such as initializeMap in this case, the advantage is you move the control of when run init to your own program. Maybe your class should not init ASAP but only your program told to do so. Other advantage is you can control the return value, or raise exception if needed (you cannot raise exception in static initializer block).

Note that the static method above is not safe and should not call concurrently. Other word, you should make sure only one thread call that method for initialize map. Otherwise, you must add lock to control multiple thread access.

Some other notes about advantages of using static initializer block:

  • Handle concurrency access automatically provided by Java.
  • Some program we don't know exactly where to put static method, so using static initializer is a safe choice.
  • Some complex initialize cannot be done in one line, so static initializer is the only choice.
Hulk
  • 6,399
  • 1
  • 30
  • 52
hqt
  • 29,632
  • 51
  • 171
  • 250
0

You have static blocks to do more complex initialization, like for instance this upload queue where you just want to make sure a directory exists.

static {
    File f = new File(getUploadDir());
    if(!f.exists()) {
        //noinspection ResultOfMethodCallIgnored
        f.mkdir();
    }
}

You can also use it to set some properties on static objects. Here's an example:

private static final SimpleDateFormat mDateTimeFormat = new 
      SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);

static {
    mDateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
millibit
  • 175
  • 1
  • 7
  • Complex intializer is the only real reason to use a static initializer. The example here isn't especially complex: you could easily factor this into a static method that you call from the field initialization. – Andy Turner Sep 16 '18 at 16:04
  • Good Answer, but `SimpleDateFormat` and `TimeZone` were both supplanted years ago by the *java.time* classes, specifically `DateTimeFormatter`, `ZoneId`, and `ZoneOffset.UTC`. – Basil Bourque Sep 16 '18 at 17:05
  • Basil: Good point. The main objective was to demonstrate initialization. Andy: Yes, you can make a static method called from a field initializerI'm not too fond of it, because you can also invoke that code at a later time. In this way, the language is clearly used to say: This shall be done only once. – millibit Sep 17 '18 at 09:39