Static Variable


Static variables

* If the value of a variable is not varied from object to object then it is not recommended to declare a variable as an instance variable. We have to declare such type of a variable at class level by using a static modifier.

* In the case instance variables for every object as a separate copy will be created but in the case of static variables a single copy will be created at the class level and shared by every object of the class.

* Static variable should be declared within the class directly but outside of any method, block or constructor.

* Static variable will be created at the time of class loading and destroyed (at the time of class unloading), hence the scope of the static variable is exactly same as the scope of the .class file. Internal steps for the load to unload a class
a. Start JVM
b. Create and start main Thread.
c. Locate .class file
d. Load .class (static variable creation)
e. Execute main() method
f. Unload .class (static variable termination)
g. Terminate main Thread h. Shutdown JVM

* Static variable will be stored in method area.

* We can access static variables either by object reference or by className but recommend to use className.

* Within the same class is not required to use class name and we can access directly.

* We can access the static variable directly from both instance and static areas.

* For static variable JVM will provide default values and we are not required to perform initialization explicitly.

* Static variable also known as class level variable or fields.