static variable in java

  • Static variable is created a single copy at class level and shared by all object of that class.
  • This variable is declare within the class directly with static modifier.
  • It is creating at the time of class loading and destroy at the time of class unloading.
  • If the value of variable is not varied from object to object then such type of variable is declare with static modifier.
  • This variable can be access from both instance and static area, either by object reference or by class name.
  • There are not required to perform any explicit initialization. jvm will always provide default values.
  • Static variable is stored in Method Area.
  • In same class we can access this variable directly.
				
					public class StaticVariableTest {

	static int y = 20;
	static int x;

	public static void main(String[] args) {

		StaticVariableTest s = new StaticVariableTest();

		System.out.println("with object reference value of y :- " + s.y);
		System.out.println("with class name value of y :- " + StaticVariableTest.y);

		System.out.println("default value of x is :- " + x);
	}
}
				
			

Output :-
with object reference value of y :- 20
with class name value of y :- 20
default value of x is :- 0