As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.
But I do not understand why we ne
I would say static block
is just syntactic sugar. There is nothing you could do with static
block and not with anything else.
To re-use some examples posted here.
This piece of code could be re-written without using static
initialiser.
Method #1: With static
private static final HashMap MAP;
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
Method #2: Without static
private static final HashMap MAP = getMap();
private static HashMap getMap()
{
HashMap ret = new HashMap<>();
ret.put("banana", "honey");
ret.put("peanut butter", "jelly");
ret.put("rice", "beans");
return ret;
}