What is difference between final, finally and finalize?

The terms "final," "finally," and "finalize" are distinct concepts in Java. Here's an explanation of each with examples:

final

The keyword "final" is used to declare a variable, method, or class in Java. When applied to a variable, it indicates that its value cannot be changed once initialized. When used with methods, it means that the method cannot be overridden by subclasses. And when applied to a class, it denotes that the class cannot be subclassed.

final int MAX_VALUE = 10; // The value of MAX_VALUE cannot be changed once assigned. final class FinalClass { // This class cannot be subclassed. } public final void doSomething() { // This method cannot be overridden by subclasses. }

finally

The "finally" block is used in exception handling to specify a code block that is guaranteed to execute, regardless of whether an exception occurs or not. It is typically used to perform cleanup operations or release resources.

try { // Code that may throw an exception } catch (Exception e) { // Exception handling } finally { // Code that always executes, regardless of exceptions // Cleanup operations or resource release }

finalize

"finalize" is a method defined in the Object class in Java. It is called by the garbage collector before an object is reclaimed by memory management. It allows an object to perform any necessary cleanup actions before being destroyed.

class MyClass { // Other class members @Override protected void finalize() throws Throwable { // Cleanup actions before object destruction // Closing open connections, releasing resources, etc. super.finalize(); } }

Conclusion

The usage and behavior of each concept are distinct. "final" is used for immutability and restriction, "finally" is used for exception handling and cleanup, and "finalize" is used for performing actions before object destruction.