Google News
logo
Java Static Block
Static Block :
1) The static blocks are executed at the time of class loading into the memory. 

2) Whenever we are using (java className) the class is loaded into the me memory at that moment the static blocks are loaded 

3) The static blocks are executed at only one time for each and every class loading. But the instance blocks are executed based number of constructor’s execution. 

4) Without using main method it is possible to print some statements into the console in java language with the help of static blocks. but this rule is applicable only up to 1.5 version if we are using higher versions if we want to execute static block the main method is mandatory 

5) In the higher version the static blocks are executed only if the class contains main method. 

6) Based on the above reason we can say in the higher version it is not possible to print some statements into the console without using main method. 

7) Whenever we are loading child class into the memory then automatically parent class is loaded hence the parent class static block is executed first and then child class static blocks are loaded.
Static Block program
class Test
{ 
static 
{ 
System.out.println("freetmielearn"); 
System.exit(0); 
} 
}
Output :
freetmielearn
the instance blocks and static blocks in the parent and child class relation.
class Test1 
{ 
static 
{ 
System.out.println(" parent class static block"); 
} 
{ 
System.out.println("parent class instance block"); 
} 
}; 
class Test extends Test1 
{ 
static 
{ 
System.out.println("child calss static block"); 
} 
{
System.out.println("child class instance block 1"); 
} 
public static void main(String[] args) 
{ 
Test t=new Test(); 
} 
};
Output :
output:Parent class static block Child class static block parent class instance block child class instance block 1