What does it mean static{}

I am looking at one Java source and inside a class it has a statement

static {

// some initialization going on


So what does this mean? There is no method name, no public/private etc. just static {}

What does it mean and what does it do?

Thanks. The first part you did not have to explain to me, I have pretty solid experience with OOP in php and javascript. It’s just I am new to Java and never heard of this concept of static block, never seen it in a book I’m using or any online videos I’m using to learn Java.

It’s all clear to me now.

In Java the ‘static’ keyword is used to denote existence of non-instantiated things.

An attempt to explain:

An Object is instantiated (created) when the new keyword is used.
eg: String string = new String( “string” );
A String named string now ‘exists’ and can be used.

However, sometimes we don’t want or need an Object to be created in order to accomplish some mundane task, so, we use the static keyword to make a variable or method available without an actual Object being created.

eg: int n = Integer.decode( “1234” );

Here the Integer static method decode has been used, without first creating an Integer object. Because decode is static, it simply ‘is’ and may be used at any time.

Now, that covers variables and methods, but what about the subject of your question? What you have is a ‘static block’, a bit of code that is executed when the class is loaded by the class loader, not instantiated, simply when loaded to be available for the program.

Imagine, if you will, that Integer.decode() above needed to use a computed lookup table to be able to convert Strings to ints, that table could be initialized at class load time to avoid the delay later on during the program by placing the init code within a static block.

Also, because static promotes an item from being a member (or instance) item to a class item, its state is available to all instances of that class.

Because an item is available, at any time, without an instance being created, (let’s say the item is an ArrayList) it must first be initialized. We cannot wait until the constructor is called because the ArrayList is referred to in some static method, hence, static block.