Pages

get our extension

Search program

Tuesday, 23 July 2013

what is the difference between instance variable and static variable(class variable)

Instance variable

--> instance variable is a variable whose seperate copy is availabe to each object.

--> instance variables are created in the objects on heap memory.





Instance_variable_example.java

class Instance_var
{
      int a=5;
       void display()
      {
            System.out.println("a="+a);
      }
      }
class Instance_variable_example
{
      public static void main(String[] args)
      {
            Instance_static obj1=new Instance_static();
            ++obj1.a;
            obj1.display();
            Instance_static obj2=new Instance_static();
            obj2.display();
           
      }

}

OUTPUT:

a=6
a=5


Static variable

 --> a static variable(also known as class variable) is a variable whose single copy in memory is shared by all objects.

--> static variables are stored on method area.



Static_variable_example.java

class Static_var
{
      static int a=5;
      static void display()
      {
            System.out.println("a="+a);
      }
      }
class Static_variable_example
{
      public static void main(String[] args)
      {
            Instance_static obj1=new Instance_static();
            ++obj1.a;
            obj1.display();
            Instance_static obj2=new Instance_static();
            obj2.display();
           
      }


}

OUTPUT:

a=6
a=6


No comments:

Post a Comment