Wednesday, May 9, 2012

Final,Finally and Finalize keyowrds in Java explained

final, finally, and finalize are keywords (and a method) in Java that despite their common naming are used for completely different purposes. It seems that because of this very reason interviewers like to ask questions about the differences between final, finally and finalize. So, in order to get a better understanding on this issue, here's my brief explanation of the final and finally keywords, and the finally method, along with relevant examples:

Lets us start with Final Keyword
  •  final can be used to mark a variable "unchangeable"
  •  private final int test = 20;  //the reference name can never change
  •  final marked method cannot be overridden.
It is used for constant, method or class declaration. When used with constants, their values cannot  be changed later, when used with methods, they can't be overridden by subclasses, final classes can’t' be derived or inherited by other classes.

  • Final keyword can be applied to vairables, method, and class.
  • final variable - You can't reassign/modify values to the variables.
  • Final class- You can’t extends (inherit) the class.
  • Final method- You can’t override the final methods

On the other hand, if you declare a class as final, then you will not be able to extend it. Whereas, if you declare a method as final, you will not be able to override it. When should you declare classes and/or methods final depends on your Object-Oriented Design.For example all kinds of strings are final by default.

Now let us discuss finally
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. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finally is used in a try/catch statement to execute code "always"
lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error
}

      
  • finally is used in try-catch (i.e. exception handling in java).
  • Each try contain only one finally blocks not more than one.
  • There is no statement between catch block and try block.
  • It will be executed if exception is occurring or not.    
  • Mostly used for memory release.

The only time that a finally block is not executed, is when there's a System.exit() call within the try or catch blocks, which actually terminates the Java Virtual Machine. It should also be noted that the finally block must be placed immediately after the catch block; or if there's no catch block, then it should be placed immediately after the try block. A typical implementation example for the try/catch/finally blocks would be:

 try

{
out = new BufferedWriter( new FileWriter( outputFile ) );
out.write( message );
} catch( IOException ioe ) {
  // Handle the exception
} finally {    
if( null != out ) {
out.close();
}
}

Lastly let us discuss  finalize()
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.

finalize is called when an object is garbage collected. You rarely need to override it. An example:

 public void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}
 This is method used to release the occupied memory.But the major condition is there is no certainly that a method call will result in the garbage cleanup. The cleanup is done on need to need basis by JVM.
finally method must be protected or public otherwise compile time error will be resulted.

This  tutorial has been written by Akhil , his E-mail id is :- akhil.killawala@gmail.com
for feedback/Suggestion please contact :- javatute@gmail.com

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP