final vs finally vs finalize() in Java — and Why finalize() Is Dead
Three keywords, one sound, three completely unrelated jobs. Interviewers love this question because it catches people who memorized definitions without understanding mechanics. Let's fix that — with code you can run.
1. final: a promise the compiler enforces
final means "this cannot be reassigned / overridden / extended" — and what it applies to changes the meaning:
- final variable — assigned exactly once. A
finalreference can't point at a different object, but the object itself can still mutate (unless it's immutable too). - final method — cannot be overridden in subclasses.
- final class — cannot be extended at all (
Stringisfinal; that's part of why it's safe).
public class FinalDemo {
public static void main(String[] args) {
final int maxRetries = 3;
// maxRetries = 4; // COMPILE ERROR: cannot assign a value to final variable
final StringBuilder sb = new StringBuilder("a");
sb.append("b"); // fine: the OBJECT mutates...
System.out.println(sb); // ab
// sb = new StringBuilder(); // COMPILE ERROR: the REFERENCE is final
}
}
final class Config { } // no subclassing, ever
// class EvilConfig extends Config { } // COMPILE ERROR
ab
The decision rule: use final on locals and fields by default — it turns accidental reassignment into a compile error instead of a debugging session. And remember the trap: final on a reference is not immutability of the object.
2. finally: the cleanup guarantee
finally is a block that runs no matter how the try exits — normal return, exception, even an early return:
import java.io.*;
public class FinallyDemo {
static String readFirstLine(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine(); // even THIS return doesn't skip finally
} finally {
br.close(); // always runs: normal exit, exception, or return
}
}
public static void main(String[] args) throws Exception {
java.nio.file.Files.writeString(java.nio.file.Path.of("/tmp/demo.txt"), "hello");
System.out.println(readFirstLine("/tmp/demo.txt"));
}
}
hello
The modern replacement: try-with-resources (Java 7+) does the finally-close ceremony for you, and it handles the suppressed-exception bookkeeping that hand-written finally gets subtly wrong:
static String readFirstLineModern(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} // br.close() called automatically, exceptions properly suppressed
}
The decision rule: never write finally { close(); } in new code — use try-with-resources. Reach for an explicit finally only when the cleanup isn't a simple close() (releasing a lock, resetting a flag).
3. finalize(): the method that must not be named
finalize() was Java's original cleanup hook: the garbage collector would call finalize() on an object before reclaiming it, so you could release native resources. It sounded reasonable. It was a disaster:
- No timing guarantee. The GC might call it seconds later, hours later, or never. A resource released "eventually" is a resource leak with extra steps.
- It slowed down garbage collection — finalizable objects needed two GC passes instead of one, and a slow
finalize()could stall the whole collector. - It could resurrect objects — assigning
thisto a static field insidefinalize()brought dead objects back to life. Yes, really.
So Java deprecated it (Java 9), then deprecated it for removal (JEP 421, Java 18). The replacements, in order of preference:
- try-with-resources / explicit
close()— deterministic cleanup you control. java.lang.ref.Cleaner(Java 9+) — for the rare case where you genuinely need cleanup tied to GC, withoutfinalize()'s pathologies.
import java.lang.ref.Cleaner;
public class NativeHandle implements AutoCloseable {
private static final Cleaner cleaner = Cleaner.create();
private final Cleaner.Cleanable cleanable;
public NativeHandle() {
long nativePtr = allocateNative(); // pretend native resource
this.cleanable = cleaner.register(this, () -> freeNative(nativePtr));
}
@Override public void close() { cleanable.clean(); } // deterministic: use this
private static long allocateNative() { return 42L; }
private static void freeNative(long ptr) { System.out.println("freed " + ptr); }
public static void main(String[] args) {
try (NativeHandle h = new NativeHandle()) {
System.out.println("using handle");
} // close() -> clean() -> freeNative runs HERE, deterministically
}
}
using handle
freed 42
The decision rule: if an interviewer asks about finalize(), the expected answer is that it's obsolete — deprecated for removal, never use it, use try-with-resources or Cleaner instead. Knowing why (no timing guarantee, GC cost, resurrection) is what separates a memorized answer from an understood one.
4. The interview one-liners
final= compiler-enforced "assign once / don't override / don't extend". Afinalreference is not an immutable object.finally= runs no matter howtryexits. In new code, try-with-resources replaces thefinally { close(); }pattern.finalize()= the GC cleanup hook that was unpredictable, slow, and could resurrect objects. Deprecated for removal — never use it.
Continue: Java Learning Roadmap 2026
Comments
Post a Comment