What is the difference between final, finally and finialize?

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change 

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; } 

finally is used in a try/catch statement to execute code "always"

try { 
  //do stuff 
} catch (SomeException se) { 
  //handle se 
} finally { 
  lock.unlock(); //always executed, even if Exception or Error or se 

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) 

A final class variable is one whose value cannot be changed.
A final method is one that cannot be overriden (define with new behavior in subclasses).
A final class cannot be inherited.
When a class is marked final, it cannot be subclassed. When a method is marked final, it cannot be overridden by the subclass. And when a field is marked final, its value once set, cannot be reset.

It is a block of statements that definitely executes after the try catch block. 
finally is the last clause in a try...catch block. It is a block of statements that is executed irrespective if or if not an exception was caught in the preceding try block.

This method will be executed when the object is garbage-collected. finalize is a reserved method in Java, which can be overridden by classes containing code to release any expensive resources being held to by the object. Expensive resources include, native peer objects, file/device/database connections.

People who read this post also read :


Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More