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

6 minbeginnerfinalfinallyfinalizekeywords

Quick Answer

final is a modifier that prevents reassignment (variable), overriding (method), or subclassing (class). finally is a block that always executes after a try/catch, used for cleanup. finalize() was a deprecated Object method the GC could call before reclaiming an object; it's unreliable and replaced by try-with-resources or Cleaner.

Detailed Answer

Despite the similar spelling, these three are unrelated:

  • final (modifier): applied to a variable (can't be reassigned after initialization), a method (can't be overridden), or a class (can't be subclassed).
final int MAX = 100;      // constant reference
class Utils { final void helper() {} } // can't override
final class ImmutablePoint {}          // can't extend
  • finally (block): part of try/catch/finally, guaranteed to run whether or not an exception occurred (barring System.exit() or JVM crash) — used for cleanup like closing resources.
try {
    risky();
} finally {
    cleanup(); // always runs
}
  • finalize() (method, deprecated since Java 9, slated for removal): an Object method the GC might call before reclaiming an unreachable object, meant for last-resort resource cleanup. It's unreliable (no guarantee it runs promptly, or at all), hurts GC performance, and can resurrect objects. Modern code uses try-with-resources (AutoCloseable) or java.lang.ref.Cleaner instead.