Monday, 8 February 2016

Instance,static and local variables in JAVA

Variables are classified based on storage and place where we are declared.

Based on storage:
v  Reference variables: Used to holds object references
              Ex: String s = “raju”; // s is reference variable
                       SampleDemo  sd = new SampleDemo(); // sd is reference variable
v  Primitive variable: Used to holds primitive values
                                                   Ex: int i=10;
                                                   char c=‘s’; 

Based on place where we declared:
             v  Instance variables
             v  Static variables
             v  Local variables
        
            Instance variables:
v   Instance variables are object level variables
v  For each object one separate instance variable will creates
v  Each instance variables will get default values which is depends on the variable declared type
v  These variables are activated wherever object creates and gets deactivated whenever the object destroyed by the Garbage Collector
v  All instance variables will store in Heap memory
v  We should declare the variables outside the methods of a class
v  Object is used for accessing the instance variables

              Static variables:
v  A single copy of the static variable will be shared by all the instances of same class
v  A static variable will be creates at the time of class loading time into memory and it destroyed at the time of class unloaded from the memory
v  Static variable will gets default values
v  Static will have “static” modifier
              Ex: static int i;
v  Static variables should define outside of all the methods of a class
               Ex: Student s1 = new Student();
                      Student s2 = new Student();
v  Class name is enough for accessing the static variables

                 Local variable:
v  The variables which are declared in a method or as a method arguments or in a constructor or in block are called local variables
v  Local variable will not get default values
v  Before using the local variables must initialized

v  Otherwise we will gets compilation error

No comments:

Post a Comment