What is Finalize method?

Finalize method is used to remove garbage from the program. As we use to write program and creates many of the objects in that program. Some of the object is useful but some objects are not in use.

Finalize keyword removes unwanted objects from program. This method is already present in program and JVM already gives garbage collector to program. But user can also call the garbage collector i.e finalize method explicitly. When JVM calls garbage collector then it is command. Means it should execute and collect the garbage. But when user call garbage collector i.e finalize method, it is request, there may be chances that it may not execute. As request can be accepted or cannot be accepted.

Hence,in simple words when JVM calls garbage collector it should execute and remove unwanted garbage from program. When user use this method it can execute or not execute. We can call finalize() method using System.gc(). When

For example:

class A{

protected void finalize(){

System.out.println(” From finalize”);

}

public static void main(String[] args)

{

A a = new A();

a=null; //here as reference is null then object is not in use

System.gc();

}

}

Output: From finalize

In above Example, as reference of object is null, the object also become null. As object become null it is not in use. Then by using finalize() method we removed that object and clear the program.

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?