Why do we use static blocks when we already have static methods?

1417 views java
7

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.

answered question

Just think, you have a static method, where you can invoke it, if the class don't have main method

Where would you run the static method from?

@MaruthiAdithya that is absolutely not what a static intializer block does.

Yes, true @AndyTurner.

I never use them. I very much dislike this construct. It's a bit opinion based to ask it in the way you asked it. Best is to understand exactly what they do, then you can decide yourself.

4 Answers

6

I assume you are referring to static initializer blocks?

static { ... }

They are blocks for initializing the class. They are run exactly once, when the class is loaded. They don't return anything.

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;
}

Static methods can be invoked at any time. They don't necessarily initialize things. They can return a value, and throw checked exceptions.

posted this
5

Static blocks provide a way of making multiple variables static at once. You may want all the fields in a particular part of your code to be static. Instead of creating a method for this, it could be more convenient to simply use a static block. Static blocks don't return anything, they are just pseudo-separated blocks of code.

This is how a static block looks:

static{
    //  your code
}

This is how a static method looks:

public static void makeStatic(){

    //  your code again..errr

    }

posted this
2

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 void static insert(String key, String value) {
       map.put(key, value);
   }
}

If we use static block for initialize object, 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. 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 static init 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.

posted this
6

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"));
}

posted this

Have an answer?

JD

Please login first before posting an answer.