Monday, 14 October 2013

Static Keyword in java

Advertisement

Static in java can be defined in various ways according to its use, like we have a static variable , a static method and a static initialization block but the common of all above three type is that all get initialized at the time of Class Loading . Let got in dept of all these three types of static type definition in java.

Basically in java we are mainly dealing with Object and Static functionality. And both are independent of each other it means static has no concern with Object and vice-versa.

Why Static has no concern with Object ?
It is because Static is a part of class that means no need to create any Object to access any static member . It can be accessible with the class name like,

< Class_name > . < Static_member >  ; 

Why Static has introduced into java ?
It is because to work with one time memory creation through out the program. But the same is not in the case of Object, for every Object JVM is going to allocate memory for it whether it is going to be used in the program or not, that means there may be chance of wastage of memory and with the static keyword JVM is going to allocate memory for one time only at the loading time and can be modified by any number of object and hence the modified value will be updated at the memory location of static member.

Static Variable 

It is a class variable which means it can be accessible without creating any object. Its memory is once created at the class loading time and can be modified multiple times and memory remain through the program. Default value of any static variable is zero . For details on Static variable click here For Details on Static Variable click here !

Syntax for declaring Static variable :
< static >  < data_type >  < var_name >  =  < value > ;

Static method 
Like static variable we can also define any method in java as static . Declaring a method as static means it can be accessible without creating object and with the class name.

Syntax for declaring static method :
< static >  < return_type >  < method_name > ( ) { }  

for ex-
static void fun_name ( ) {
}


Static initialization block 

It is a static block and again it will be executed first of it is available in the java program because it is loading first by the JVM.

Syntax for declaring Static initialization block :
< static > {  }

for ex-
static {
System.out.println ( " Static initialization Block" ) ;

}


EmoticonEmoticon