Tuesday, May 25, 2010

Difference between final, finally and finalize

Final is used to declare constants as shown in below example.

int final a = 10;

Class can also be a final class, which shows that the class can't be subclassed.

Method can also be final method, which shows that the method can't be overridden.

Finally is used to release any resources used in try catch block to free memory. It is placed after try-catch block. Code in finally block is executed always irrespective of the exception thrown except when System.exit(0) is called. It is shown in the below example

try
{
System.out.println("Enter your name:");
String name = scan.next();
System.out.println(name);
}
catch(IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
finally
{
scan.close();
System.out.println("Closed");
}
Code in finally block is get executed. If you put System.exit(0) inside try block or inside catch block, then finally block is not called.

finalize() method is called before an object is collected by garbage collector to free any resources being used by that object

2 comments: