Skip to content

Commit 5d52b11

Browse files
committed
Add finalize method and its usage
1 parent 6bf0ce0 commit 5d52b11

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

README.md

+47
Original file line numberDiff line numberDiff line change
@@ -504,4 +504,51 @@ Frequently asked Java Interview questions
504504

505505
**[⬆ Back to Top](#table-of-contents)**
506506

507+
16. ### What is finalize method? How do you override it?
508+
The `finalize()` is a method from the Object class used to perform cleanup activity before destroying any object. The method is invoked by garbage collector for cleanup activities like closing the resources associated with an object(database connection or network connection). This process is known as **finalization** and it helps JVM for in-memory optimization.
509+
510+
It is a protected method of Object class with syntax as shown below,
511+
```java
512+
protected void finalize() throws Throwable{}
513+
```
514+
515+
Since Object is the superclass of all java classes, the finalize method is available for every java class. That's why garbage collector can call the `finalize()` method on any java object.
516+
517+
This method has empty implementation inside Object class. If your class has clean-up activities, you need to override this method. The following example demonstrate how to override the finalize method and call the method explicitly.
518+
519+
```java
520+
import java.lang.*;
521+
522+
public class finalizeDemo {
523+
524+
protected void finalize() throws Throwable {
525+
try {
526+
527+
System.out.println("Inside finalize() method of finalizeDemo class");
528+
}
529+
catch (Throwable e) {
530+
531+
throw e;
532+
}
533+
finally {
534+
535+
System.out.println("Calling finalize method of the Object(super) class");
536+
537+
super.finalize();
538+
}
539+
}
540+
541+
public static void main(String[] args) throws Throwable {
542+
finalizeDemo fd = new finalizeDemo();
543+
fd.finalize();
544+
}
545+
}
546+
```
547+
548+
The statement `super.finalize()` is called inside finally block to ensure its execution even in the case of exceptions.
549+
550+
**Note:** The garbage collector invokes the `finalize()` method only once on any object.
551+
552+
**[⬆ Back to Top](#table-of-contents)**
553+
507554
<!-- QUESTIONS_END -->

0 commit comments

Comments
 (0)