• finalize() method pre defined method which is present in java.lang.Object class.
  • finalize() method is protected  method defined in java.lang.Object class.

  1. protected void finalize() throws Throwable{
  3. }

1.What is purpose of overriding finalize() method?

  • The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

2.How many times does the garbage collector calls the finalize() method for an object? 

  • Only once.

3.What happens if an uncaught exception is thrown from during the execution of finalize() method of  an object?

  •  The exception will be ignored and the garbage collection (finalization) of that object terminates

  •  If we are overriding finalize() method then its our responsibility to call finalize() method explicitly.

  •  finalize() method never invoked more than once by JVM or any given object.
  • There is no guaranty that if we call finalize() method but we can force garbage collector by calling below two methods
  • System.gc();
  • Runtime.getRuntime().gc();

#1 : Java program to explain about finalize() method

  1. package inheritance
  2. public class B {
  3.  /**
  4.  * Finalize() method in java
  5.  * @author www.instanceofjava.com
  6.  */
  7.   @Override
  8.   protected void finalize() throws Throwable {
  9.             try{
  10.                 System.out.println("Inside Finalize() method of Sub Class : B");
  11.             }catch(Throwable t){
  12.                 throw t;
  13.             }finally{
  14.                 System.out.println("Calling finalize() method of Super Class:  Object");
  15.                 super.finalize();
  16.             }
  18.  }
  20. public static void main(String[] args) throws Throwable{
  21.         B obj= new B();
  22.         String str=new String("finalize method in java");
  23.         str=null;
  24.         obj.finalize();
  26.         }
  27. }

finalize() method in java with example program

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
Newer Post
Older Post

No comments

Leave a Reply

Select Menu