by Dinesh Thakur

The static modifier is associated only with methods and variables, not classes. The static modifier is used to specify variables that can only be declared once. Static methods are used to specify methods that should not be overridden in subclasses.

1. When the variable is declared outside the method, block and constructor using static modifier then it is treated as static variable.
2. Like instance variable if it is not initialized then it takes the default value of the data type.
3. It can use any access specifier.
4. It is accessed within the static method, non-static method and constructor through the class name or object name or directly without creating any object.
5. Static variable is also treated as class variable and it is initialized at the class loading time. So, there is always one copy of static variable.
6. Before the program is exectued classloader load the class sale in jvm occupied memory space, at class loading time classloader initialize static variable.
7. As classloader load the class sale only once, so there is only one copy of static variable.

Here is the Java Example for the program Static Variable :

public class StaticVariableInJavaExample
{
          private static int i; //static variable.
          void show()
         {
             i++;
         }
         public StaticVariableInJavaExample()
        {
             i+=5 ;
        }
       static void Display()
       {
StaticVariableInJavaExample StVar=new StaticVariableInJavaExample();
            StVar.i++;
            System.out.println(i);
       }
public static void main(String args[])
      {
           Display();
StaticVariableInJavaExample StVar = new StaticVariableInJavaExample();
          StVar.i+=10;
          StVar.show() ;
          System.out.println(StVar.i);
     }
}

Static Variable In Java Example