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?
Yes. It is possible to define multiple static blocks in a java class.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With