Sourav
Sourav

Reputation: 21

When to use static initial block in JAVA?

Can anyone please explain me in which scenario we use static initial block?

Upvotes: 0

Views: 134

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Another example is java.lang.Object

public class Object {

    private static native void registerNatives();
    static {
        registerNatives();
    }
...

Upvotes: 0

Matt Klooster
Matt Klooster

Reputation: 767

I use them all the time to initialize lists and maps.

List<String> myList = new ArrayList<String>(){{
    add("blah");
    add("blah2");
}};
for(String s : myList){
    System.out.println(s);
}

Upvotes: -3

Scott Stanchfield
Scott Stanchfield

Reputation: 30644

You can use it as a "constructor" for static data in your class. For example, a common situation might be setting up a list of special words:

private static final Set<String> special = new HashSet<String>();
static {
    special.add("Java");
    special.add("C++");
    ...
}

These can then be used later to check if a string matches something interesting.

Upvotes: 7

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

And another common one is when some of the code you need to use to create your statics throw exceptions.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240890

The most common scenario is loading some resources on class load, for example loading library for JNI

Upvotes: 3

Related Questions