Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Block in Java [duplicate]

Tags:

java

static

I was looking over some code the other day and I came across:

static {     ... } 

Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?

like image 555
Mohit Deshpande Avatar asked May 31 '10 12:05

Mohit Deshpande


People also ask

Can we have multiple static block in Java?

Yes. It is possible to define multiple static blocks in a java class.

How many times static block is executed in Java?

Therefore, only one time static block will be executed. Note: Instance block and constructor both are executed during the object creation but instance block will execute first before the execution of the constructor during the object creation.

What are static blocks in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.

Can we inherit static block in Java?

No,They never participates in inheritance. because staticblock is used for initializing static data member similarly instance is for initializing instance datamembers. Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads.


2 Answers

It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).

It can be thought of as a "class constructor".

Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.

like image 182
Joachim Sauer Avatar answered Oct 15 '22 10:10

Joachim Sauer


It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.

From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

If you have a class with a static look-up map it could look like this

class MyClass {     static Map<Double, String> labels;     static {         labels = new HashMap<Double, String>();         labels.put(5.5, "five and a half");         labels.put(7.1, "seven point 1");     }     //... } 

It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.

like image 34
aioobe Avatar answered Oct 15 '22 11:10

aioobe