Wednesday, February 26, 2014

All about final keyword in java


  1. final is a keyword to represent final version
  2. final can be used for classes, methods and variables
  3. if final is used for a class, that class can not be inherited. java.lang.String is the best example for final class from java API.
  4. if final is used for a method, that method can not be overridden
  5. if final is used for a variable, that variable becomes constant.




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