Reputation: 21
Can anyone please explain me in which scenario we use static initial block?
Upvotes: 0
Views: 134
Reputation: 136002
Another example is java.lang.Object
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
...
Upvotes: 0
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
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
Reputation: 65811
And another common one is when some of the code you need to use to create your statics throw exceptions.
Upvotes: 0
Reputation: 240890
The most common scenario is loading some resources on class load, for example loading library for JNI
Upvotes: 3