Easy java core-java

What is the difference between final, finally and finalize?

The 30 second answer

They're unrelated. final is a keyword: a final variable can't be reassigned, a final method can't be overridden and a final class can't be extended. finally is the block after try that always runs, whether or not an exception was thrown, so it's for cleanup. finalize was a method the garbage collector might call before freeing an object; it's unreliable, deprecated for removal since Java 18, and replaced by try-with-resources and Cleaner.

<!-- level: 1 -->

  • **final:** a variable assigned once (for an object, the reference is fixed, not the object's contents), a method that can't be overridden, a class that can't be extended (String is final). More detail is in Difference between the final keyword and a final variable?.
  • **finally:** runs after try and any catch, on normal completion, on an exception and even on return. The test below printed "finally runs before return" and then returned 1. Don't return from finally; it silently discards the exception.
  • **finalize():** a method on Object that the GC could call before reclaiming an object. JEP 421 deprecated finalization for removal in Java 18 because it is unpredictable: there is no guarantee when or whether it runs, it slows the GC and it can resurrect objects. Use try-with-resources for resources, and java.lang.ref.Cleaner as a safety net.
static int f() {
    try { return 1; }
    finally { System.out.println("finally runs before return"); }
}
Sources (2)
  1. JEP 421: Deprecate finalization for removalopenjdk.org
  2. Java Language Specification, chapter 14: Blocks, statements and patterns (14.20.2 try-finally)docs.oracle.com