Sunday, November 20, 2011

What are the differences between finalize(), final and finally


  • finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
  • finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. It allows the programmer to avoid having clean up code accidentally bypassed by a return, continue, or break. Keeping the clean up code in a finally block is always a good practice, even when no exceptions are anticipated.
  • final – This is useful in several ways...
When it is used with variable declaration, it becomes constant
When it is used with method, the method cant be overridden by the child class
When it is used with the class, the class cant have child classes.

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment