24 Dec 2017

What is Difference among final, finally, and finalize .



Difference between final, finally, and finalize:


final:
1.  final is the modifier applicable for classes, methods and variables.
2. If a class declared as the final then child class creation is not possible.
3. If a method declared as the final then overriding of that method is not possible.

4. If a variable declared as the final then reassignment is not possible

class FinalDemo {
   public static void main(String[] args) {
         final int x = 10;
         x = 20;// Compile Time Error
   }
}
finally:
1. finally is the block always associated with try-catch to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled.

class FinallyDemo{
          public static void main(String[] args) {
                   try {
                             int x = 30;
                   } catch (Exception e) {
                             System.out.println(e);
                   } finally {
                             System.out.println("finally block is executed");
                   }
          }
}
finalize:
1. finalize is a method, always invoked by Garbage Collector just before destroying an object to perform cleanup activities.
Note:
1. finally block meant for cleanup activities related to try block where as finalize() method meant for cleanup activities related to object.

2. To maintain clean up code finally block is recommended over finalize() method because we can't expect exact behavior of GC.
class FinalizeDemo {
      public void finalize() {
            System.out.println("finalize called");
      }

      public static void main(String[] args) {
            FinalizeDemo f1 = new FinalizeDemo();
            FinalizeDemo f2 = new FinalizeDemo();
            f1 = null;
            f2 = null;
            System.gc();
      }
}