Fundamentals 14 min read

Deep Understanding of Java's final, finally, and finalize Keywords

This article explains the distinct purposes, usage rules, and underlying bytecode behavior of Java's final, finally, and finalize keywords, covering class and method immutability, variable constancy, guaranteed execution blocks, deprecated finalization, and common performance misconceptions.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Deep Understanding of Java's final, finally, and finalize Keywords

final, finally and finalize

The final keyword can modify classes, methods, and variables, preventing inheritance, overriding, or reassignment; finally guarantees execution of its block after a try (or try...catch ) regardless of exceptions; finalize is a deprecated method of Object intended for cleanup before garbage collection.

final usage

final on a class makes it non‑extendable, as shown by attempting to extend FinalUsage and receiving a compile‑time error. When applied to methods, it blocks overriding, requiring the @Override annotation for non‑final methods. Applied to variables, it forces single assignment; for reference types the reference is immutable but the object's internal state can still change.

finally usage

finally is typically paired with try to ensure critical code (e.g., unlocking, closing streams) runs even if an exception occurs. It also runs before any control‑transfer statement such as return , and a finally block with its own return overrides earlier returns.

finalize purpose

finalize was designed to let objects release resources before garbage collection, but its execution time is nondeterministic and it is deprecated since JDK 9. Modern code should prefer explicit resource management (e.g., try‑with‑resources) over finalize .

performance considerations

Historically, final could enable method inlining, but modern JVMs perform similar optimizations automatically; therefore, using final for performance gains is generally unnecessary.

edge cases where finally may not run

Scenarios such as System.exit , Runtime.getRuntime().halt , JVM crashes, infinite loops in try / catch , forced OS termination, or daemon‑thread termination can prevent a finally block from executing.

JavaMemory ManagementException HandlingFinalizefinallykeywordsfinal
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.