This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Static block in Java
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Static variables are class level variables and without instantiating class we can access these variables.
Static int a;
Class loading time itself these variables gets memory
Static methods are the methods with static keyword are class level. without creating the object of the class we can call these static methods.
public static void show(){
}
Now its time to discuss about static blocks.
Static block also known as static initializer
Static blocks are the blocks with static keyword.
Static blocks wont have any name in its prototype.
Static blocks are class level.
Static block will be executed only once.
No return statements.
No arguments.
No this or super keywords supported.
static{
}
What is the need of static block?
Static blocks will be executed at the time of class loading.
So if you want any logic that needs to be executed at the time of class loading that logic need to place inside the static block so that it will be executed at the time of class loading.
To initialize the static variables while class loading itself we need static block.
If we have multiple classes then if you want to see the order of those classes loading then static block needed.
When to use static blocks?
If you want to access static variables before executing the constructor.
If you want to execute your code only once even any number of objects created.
If you want to initialize static constants.
When and where static blocks will be executed?
Static blocks will be executed at the time of class loading by the JVM by creating separate stack frames in java stacks area (Please refer JVM Architecture to know about stacks area).
Static blocks will be executed in the order they defined from top to bottom.