finally block of code always executes, whether an exception occurred or not. It’s used to run clean-type resources.
After java 7+ by using try-resources with files make finally as optional.
finally Example
In this example, you will see finally block executes, whether an exception occurred or not.
public class TesFinally {
public static void main(String[] args) {
try{
int a = 20;
int b = 0;
int result = a/b;
}catch(Exception e){
System.out.println("Exception occured: "+ e.getMessage());
}
finally{
System.out.println("Finally Exceuted.");
}
}
}
Output
Exception occured: / by zero
Finally Executed.
finalize
finalize is an object class method
finalize() method is called just before the object is destroyed or garbage collected.
finalize() method is used to clean up object resources before destroy.
If finalize() method call Explicitly, then it will be executed just like a normal method but the object won’t be deleted/destroyed.
In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.
public class FinalizeMethodTest {
public static void main(String[] args) {
FinalizeMethodTest test=new FinalizeMethodTest();
//manually calling finalize method is call like normal method
test.finalize();
//unreferenced object to make eligible for garbage collector
test=null;
//Requesting JVM to call Garbage Collector method
System.gc();
System.out.println("Main Method Completed !!");
}
@Override
public void finalize()
{
System.out.println("finalize method overriden");
}
}
Output
finalize method overriden
Main Method Completed !!
finalize method overriden
Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.
You must be logged in to post a comment.