Saturday, May 25, 2013

1. static variable vs instance variable ?

static variable is class variable, It can be accessed by using class name as well whereas instance variable is related to instance. One copy of each instance variable is created for every object of the class

See programmatic example below
class A
{
   int  i;
   static int j;
}

class Test
{
  public static void main(String args[])
   {
    A oa1 = new A();
    oa1.i = 10;
    oa1.j = 10;
    A oa2 = new A();
    oa2.i = 20;
    oa2.j = 20;
    System.out.println("oa1.i = "+oa1.i);
    System.out.println("oa1.j = "+oa1.j);
    System.out.println("oa2.i = "+oa2.i);
    System.out.println("oa2.j = "+oa2.j);
    System.out.println("A.j = "+A.j);
  }
}

output

oa1.i = 10
oa1.j = 20
oa2.i = 20
oa2.j = 20
A.j = 20