Static Blocks in Java


The static blocks are anonymous blocks of code that can be written while defining classes. They get executed when the Class template is loaded in the memory by JVM. Please note that they get loaded while the Class template is being loaded and not when a new object is being created. So there is every chance that the static block will get executed only one during the entire runtime of a program.

This fact makes static blocks a good place to write some initialization stuff. The above example show how it is done.

One More Point: I found that , Just declaring a class variable does now load it in memory (Yes, the declaration got executed but against my expectations the static block was not executed.). The class template gets loaded only when we create a new object. And yes it stays loaded. Hence, further object creations will not invoke the static block.



EXAMPLE CODE:-


Class A: The class where we have written the static block.
Class B:- A Class where we have referenced ClassA, so that its template gets loaded in the memory.
Launcher_Class:- Its sole purpose is to house the main function and trigger the whole scenario by instantiating ClassB.

------------------CODE BEGINS------------------------

package testing_static_blocks;

public class ClassA
{

static{

System.out.println("Here I Load !!!!!!!");
}

}

------------------------------------------------------------------------------------
package testing_static_blocks;

public class ClassB
{

int x;
char y;
public ClassB()
{
new ClassA();
}



public void some_method()
{
x=10;
y='c';

}
}

------------------------------------------------------------------------------------


package testing_static_blocks;

public class Launcher_Class
{

public static void main(String[] args)
{

new ClassB();
}

}
----------------CODE ENDS-------------------------------



Til Next Time
Adios.

No comments:

Post a Comment