Sobes.tech
Junior

What are the final and finalize keywords in Java, and how do they differ?

sobes.tech AI

Answer from AI

In Java, final and finalize are different concepts with different purposes:

  • final is a keyword used to declare:
    • Constants (variables that cannot be changed after initialization).
    • Methods that cannot be overridden in subclasses.
    • Classes that cannot be inherited.

Example:

final int x = 10; // x cannot be changed
final class MyClass {} // class cannot be inherited
final void myMethod() {} // method cannot be overridden
  • finalize() is a method of the Object class, called by the garbage collector before an object is removed from memory. It is intended for resource cleanup, but its use is not recommended because its invocation is not guaranteed and may lead to unpredictable behavior.

Example:

@Override
protected void finalize() throws Throwable {
    // resource cleanup
    super.finalize();
}

Differences:

  • final is a keyword for controlling code modification.
  • finalize is a method for cleanup before garbage collection, but it is deprecated and not recommended for use.