InterviewSolution
Saved Bookmarks
| 1. |
What is the "finalize" method used for in Java? Give an example illustrating the use of the "finalize" method. |
|
Answer» Before an object is destroyed, the "finalize" method or function is used to conduct cleanup operations on unmanaged resources OWNED by the current object. Because this method is PROTECTED, it can only be accessed through this class or a derived class. The syntax of the finalize method is given below: protected void finalize throws Throwable{}An example illustrating the use of the finalize method is given below: public class FinalizeMethodExample { public static void MAIN(String[] args) { FinalizeMethodExample o = NEW FinalizeMethodExample (); System.out.println(o.hashCode()); o = null; // a call to the garbage collector of Java System.gc(); System.out.println("The end of garbage COLLECTION!"); } @Override protected void finalize() { System.out.println("The finalize method is being called now!"); } }The output of the above program will be as follows: 3202429534The end of garbage collection!The finalize method is being called now! |
|