What is the difference between final, finally and finalize() ?

By | March 7, 2023

In Java, final, finally, and finalize() are three different concepts:

final is a keyword that can be used to declare a variable, method or class that cannot be modified or overridden. A final variable cannot be reassigned a new value, a final method cannot be overridden by a subclass, and a final class cannot be extended.

finally is a block of code that is used to execute a set of statements after a try-catch block, regardless of whether an exception is thrown or not. The finally block is optional, but when used, it is executed even if an exception is thrown, caught, and handled by the catch block.

finalize() is a method that is called by the garbage collector before an object is destroyed. It is used to perform any final cleanup operations on an object before it is removed from memory. The finalize() method is called automatically by the garbage collector, and it is not recommended to call it explicitly in your code.

Here is an example to demonstrate the usage of final, finally, and finalize():

public class Example {
final int number = 10; // final variable
public void method() {
try {
// code that may throw an exception
} catch (Exception e) {
// exception handling
} finally {
// code that will always execute
}
}
protected void finalize() {
// final cleanup operations before object destruction
}
}

In this example, the number variable is declared as final and cannot be reassigned a new value. The method() contains a try-catch block with a finally block that will always execute, regardless of whether an exception is thrown or not. The finalize() method is used to perform final cleanup operations on the object before it is removed from memory by the garbage collector.

In summary, final is used to declare a variable, method, or class that cannot be modified or overridden, finally is used to execute a set of statements after a try-catch block, and finalize() is called by the garbage collector before an object is destroyed to perform any final cleanup operations.

Leave a Reply

Your email address will not be published. Required fields are marked *