Difference between `final`, `finally`, and `finalize` in Java.
Jul 08, 2025 am 02:30 AMIn Java, final, finally and finalize are three keywords or methods that have different functions. 1. Final is used to restrict the modification or inheritance of variables, methods and classes to ensure immutability; 2. Finally used for code blocks in exception processing to ensure that resources release and other operations are always executed; 3. Finalize is an Object class method, which was used for cleaning before garbage collection, but has been deprecated. It is recommended to use AutoCloseable or try-with-resources instead. They are used to control invariance, ensure execution after exception handling, and replace resource cleaning methods.
In Java, final
, finally
, and finalize
are three distinct terms that are often confused because of their similar spelling. However, each plays a completely different role in the language. Here's how they different and where you're likely to use them.

1. final
: A Keyword for Immutability and Control
The final
keyword is used to restrict changes. It can be applied to variables, methods, and classes, and its meaning changes slightly depending on what it modifies.

-
Final Variables : Once assigned, their value cannot change. This makes them constants.
final int MAX_SPEED = 120;
Trying to reassign
MAX_SPEED
later will cause a compile-time error. Final Methods : Prevents overriding in subclasses.
public final void startEngine() { ... }
Final Classes : Prevents inheritance. You can't extend a final class.
public final class Car { ... }
Use final
when you want to enforce immutability or prevent unwanted subclassing or method overriding.
2. finally
: Part of Exception Handling
The finally
block is used in exception handling with try-catch
. It ensures that a section of code runs regardless of whether an exception is thrown or caught.
This is especially useful for resource cleanup:
try { // open file or connection } catch (IOException e) { // handle exception } finally { // always close resources }
Even if the try
block returns early or throws an exception, the finally
block still executes — making it ideal for closing files, database connections, or network sockets.
A few things to note:
- If both
try
andcatch
have return statements,finally
still runs before the method exits. - Avoid using
return
insidefinally
— it can override any return or exception fromtry/catch
.
3. finalize
: Deprecated Resource Cleanup Method
The finalize()
method belongs to the Object
class and was originally intended for performing cleanup operations before garbage collection. It looks like this:
@Override protected void finalize() throws Throwable { // perform cleanup super.finalize(); }
However, relying on finalize()
has always been discouraged because:
- It's not guaranteed to run promptly — or at all.
- Performance issues arise due to unpredictable behavior.
- Java 9 deprecated it, and it's now scheduled for removal.
Instead of finalize()
, modern Java prefers using AutoCloseable interfaces or try-with-resources for predictable cleanup.
So, to recap:
- Use
final
to make something unchangeable or non-inheritable. - Use
finally
to ensure code runs after a try-catch block. - Don't use
finalize()
— it's outdated and unreliable.
Basically that's it.
The above is the detailed content of Difference between `final`, `finally`, and `finalize` in Java.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.
