Based on the purpose and position of declaration,all variables are divided into 3 types

  1. instance variables
  2. static variables
  3. local variables

instance variables

  1. If the value of a variable is varied from object to object such type of variables are called "instance variables"
  2. for every object a separate copy of instance variables will be created
  3. We can declare instance variables with in the class but outside of any method or constructor or initialization blocks
  4. instance variables will be created at the time of object creation and destroyed at the time of object destruction
  5. for the instance variable it is not required to perform initialization explicitly,JVM will always provide default values

Example:

class Test{
  int i;
  public static void main(String args[]){
    Test t=new Test();
    System.out.println(t.i);
  }
}
/*
Output:
0
*/

Example:

class Test{
   int i;
   public static void main(String args[]){
     System.out.println(i);
  }
}
/*
Compile time error:Cannot make a static reference to the non-static field i
*/

Static variables

If the value of a variable is common for all objects,then it is not required to declare that object at object level.We have to declare such type of variables at class level by using “static keyword“, those variables are called static variables or fields

  1. for the static variables only one copy will be created and shared by all the object
  2. static variables will be created at the time of “class loading” and will be destroyed at the time of class unloading
  3. class loading:The process of loading .class file into main memory(RAM) is called class loading

  4. We have to declare static variables with in the class directly but outside of any method or constructor
  5. There is no need to perform explicitly initialization for the static variables.JVM always provides default values
  6. Example:

    class Test{
       static int i;
       public static void main(String args[]){
         System.out.println(i);
      }
    }
    /*
    Output:
    0
    */
    

    Example:

    class Test{
      int i=10;
      static int j=20;
      public static void main(String args[]){
         Test t1=new Test();
         t1.i=100;
         t1.j=200;
         Test t2=new Test();
         System.out.println(t2.i+"...."+t2.j);
      }
    }
    /*
    Output:
    100...200
    */