Wednesday, 27 April 2016

Know about Static and Instance Blocks in Java

Static Block in Java:-
The purpose of static block is to initialize static data member’s only once static block and execute only once when the class is loaded into the main memory before executing the main method.
Syntax:-
Static
{
Block of statements (s); ……….initialize of static data members.
}
When we write a static block and main method in a single Java program then JVM executes static block first and later main method only once.
Writing block is optional when we write static block & constructors in a Java program then JVM will executes static block only once & constructors will execute each and every time.
In static block we can access / initialize only static data members but not instance data members where as both instance & static data members can be access in constructor.
In one Java class we can write any number of static blocks but all these types of static blocks will be treated as single static block and gives the output in that order in which we write.
Whenever we initialize a static data member in the class then by default that class will contain then system defined static block.
** write a Java program which will illustrate the concept of static block.
class SBEX1
{
static
{
System.out.println("I am From Static Block");
}


public static void main(String[] args)
{
System.out.println("I am from main()");
}
}
Instance Block:-
The purpose of instance block is exactly similar to default constructor of the particular class.
Instance block will execute each and every time whenever an object is created before executing the constructor and after executing the static block.
Static block will execute only once when the class is loaded in the main memory for initializing the data in main memory whereas instance block will be calling each and every time whenever an object is created before the constructor and it is used for initializing instance data members of a class.
Syntax:-
{
Block of statements (s); ……….initialize of instance data members.
}
We can write any number of instance blocks but all of the instance block will be treated as single instance block and they will be executed in which order they write.


** write a Java program which will illustrate the concept of instance block.
class IBEX1
{
static
{
System.out.println("SB...........IBEX1");
}
{
System.out.println("IB............IBEX1");
}
IBEX1()
{
System.out.println("IBEX1..........DC");
}
}


public static void main(String[] args)
{
System.out.println("I am from main()");
IBEX1 t1=new IBEX1();
IBEX1 t2=new IBEX1();


}

}

No comments:

Post a Comment