Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose/advantage of a static{} block? [duplicate]

Tags:

java

static

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?

like image 401
asteri Avatar asked Sep 18 '25 17:09

asteri


2 Answers

As they say in the Java Tutorials:

If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

like image 103
Chris B Avatar answered Sep 20 '25 09:09

Chris B


As you said, static blocs are executed at initialization time. Say that you have a static field which can be pretty complex, for example

private static List<ThingsDownloadedByTheNet> ls;

just doing

private static List<ThingsDownloadedByTheNet> ls = new ArrayList<ThingsDownloadedByTheNet>

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)

like image 24
user1610075 Avatar answered Sep 20 '25 10:09

user1610075