Saturday, 9 March 2013

Comparison of final, finally and finalize ()

final


It is a key word or access modifier to define constants.


final - Constraint


final variable  - Value cannot be changed.

final method   - Method  cannot be overridden (define with new behavior in subclasses).

final class       -  Class cannot be inherited.


finally


                It always used in conjunction with try and catch blocks

Except that, System.exit(0) call, It performs the execution always [unexpected error / exception thrown or not]


finally - Constraint


Each try contain only one finally blocks not more than one.


finalize()


                It helps in garbage collection, which is invoked before an object is discarded by the garbage collector [Called only once].

               This is method used to release the occupied memory.

finalize() - Constraints


               It can’t release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources

               finalize() method must be protected or public otherwise compile time error.

 

Example 


package com.javalearning.crazy;

public class FinalSample {

      @Override

      protected void finalize() throws Throwable {

            try {

                  final int interest = 2;

                  int rate = interest / 0;

                  System.out.println("The rate used here" + rate);

            } catch (Throwable t) {

                  throw t;

            } finally {

                  System.out.println("It performs the execution always except 

system exit call");

                  super.finalize();

            }

      }

      public static void main(String[] args) throws Throwable {

            FinalSample sampleFinal = new FinalSample();

            sampleFinal.finalize();
      }
}

No comments:

Post a Comment