Possible Duplicate:
Static Initialization Blocks
While reviewing some old code, I found some rather odd syntax that I’ve never seen before. After doing some research, I know now that what I saw was a static{} block which (if I understand correctly) is a block of code that is executed at initialization time.
What I don’t understand is the advantage to having such a feature or when one would possibly want to use this. It seems like the static blocks simply contain regular lines of code which could belong in any regular static method, so what is the advantage to having it run automatically at initialization (other than saving a programmer a line of code to call a method)? Why is this important or useful?
As you said, static blocs are executed at initialization time.
Say that you have a static field which can be pretty complex, for example
just doing
could not be enough, as you maybe want to set list elements too.
So, you do a static block, in which you perform some initialization (in this case you connect to a server and populate list elements)