Finalize Method in Java

Finalize method in Java is a special method called by the garbage collector when it has no existing reference of an object. The run-time system call its finalize() method before the memory is reclaimed. The finalize method will return no value and no arguments but can be overridden by any class. The finalize method for all current object is called when an application exits.

Finalize Method in Java

Finalize method in Java is a special method called by the garbage collector when it has no existing reference of an object. The run-time system call its finalize() method before the memory is reclaimed. The finalize method will return no value and no arguments but can be overridden by any class. The finalize method for all current object is called when an application exits.

Finalize Method in Java


Finalize method in Java is a special method called by the garbage collector when it has no existing reference of an object. The runtime system call its finalize() method before the memory is reclaimed. The finalize method will return no value and no arguments but can be overridden by any class. The finalize method for all current object is called when an application exits.

finalize() method is defined under java.lang.Object class.

Garbage collection is carried out when no references to an object exist which means that the object is no longer needed and the memory of the object can be reclaimed.

By using finalize() method, a programmer specify some actions that are performed before an object is destroyed.

The declaration for the finalize method is:

protected void finalize() throws Throwable {
super.finalize();
}

The finalize method is normally declared as protected and public. The finalize method can handle Exception try and catch.

finalize() method is called only once for an object by JVM. System.runFinalization() and Runtime.getRuntime(). runFinalization() method call finalize() method of all object eligible for garbage collection.

* There is a possibility that a finalize() method is never called as the object may never go unreachable.

Example of Finalize method in Java:

package Toturial;

class FinalizeTest {
	private String name;

	public FinalizeTest(String s) {
		name = s;
	}

	protected void finalize() {
		System.out.print(name);
	}
}
class Test {
	public static void call() {
		FinalizeTest x1 = new FinalizeTest("Java"), y1 = new FinalizeTest("Hello");
	}

	public static void main(String[] args) {
		call();
		System.gc();
	}
}

Output:

HelloJava