0

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

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

Comments

0

Another example is java.lang.Object

public class Object {

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

Comments

-3

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

5 Comments

He was asking about static initializers. That's an example of an instance (non-static) initializer.
(It is a good example of an instance initializer though, which is useful for setup in anonymous inner classes as you demonstrated)
Just be aware that that actually creates a subclass of ArrayList!
I know. It's not the most memory efficient thing either from what I've heard.
This is definitely frowned upon, creating the subclass of ArrayList. Generally, the more preferred approach for this would be: List<String> myList = Arrays.asList("blah", "blah2"); Only problem here is that you can't control the type of the List, if that is important to you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.