Difference Between final, finally, and finalize in Java

Difference Between final, finally, and finalize in Java

7 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 22, 2024 11:34 IST

Have you ever wondered about the differences between final, finally, and finalize in Java? While final is used to create constants and prevent method overriding or class inheritance, finally is a block that executes after try-catch for guaranteed execution, typically for cleanup. On the other hand, finalize is a method called before an object's garbage collection, used for final resource release tasks. Let's understand more!

"final" is a keyword used to define immutable values or unchangeable behaviours in classes and methods. "finally" is a block in exception handling that ensures the execution of code regardless of whether an exception occurs."finalize" is a method that is called by the garbage collector before an object is destroyed, typically used for cleanup activities. Each plays a crucial role in the language's structure and behaviour management. In this blog, we will understand the differences between them!

Understanding User Defined Exception in Java

Table of Content

 
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

โ€“ / โ€“
350 hours
Free
6 months
โ€“ / โ€“
4 months
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
1 month
โ‚น40 K
7 weeks
โ‚น7.8 K
3 months
โ‚น8.47 K
2 months
โ‚น7 K
6 months
โ‚น4 K
2 months

Difference Between final, finally, and finalize

Below is a table differentiating between final, finally and finalize.

Feature

final

finally

finalize

Type

Keyword

Block

Method

Usage

final is used to apply restrictions. It can be used with classes, methods, and variables. A final class cannot be subclassed, a final method cannot be overridden, and a final variableโ€™s value cannot be changed.

finally is a block used in exception handling. It follows try or catch blocks and executes regardless of whether an exception is thrown or caught. It is typically used for cleanup operations like closing files or releasing resources.

finalize is a method used in garbage collection. It is called by the garbage collector on an object when there are no more references to that object. It is used to perform cleanup operations before an object is destroyed.

Scope

The scope of final depends on where it is used. If used with a class, it affects the whole class. If used with a method, it affects just that method. If used with a variable, it affects the state of that variable.

The finally block is associated with the try-catch block where it is declared. It is executed after the try and catch blocks have completed their execution.

finalize is a method of the Object class and can be overridden by any class. The scope is within the class where it is overridden.

Purpose

To impose a constraint, to ensure immutability of a variable, or to prevent inheritance and overriding.

To ensure that a code segment is executed irrespective of whether an exception occurs or not, mainly for cleanup activities.

To give an object its last chance to release any resources and perform cleanup before it is collected by the garbage collector.

What is final in Java?

In Java, final is a keyword used to apply restrictions on classes, methods, and variables. When final is used with different Java entities, it has the following implications:

1. Final Variables

  • A final variable cannot be reassigned once it has been assigned a value. This means once a final variable has been initialized, its value cannot be changed.
  • It effectively makes the variable a constant. This is useful for defining values that should remain constant throughout the execution of a program, like final int MAX_SIZE = 100;
  • A final variable must be initialized at the time of declaration or within the constructor if it is an instance variable.

2. Final Methods

  • A final method cannot be overridden by subclasses. This is useful when you want to keep the implementation of a method unchanged in the inheritance hierarchy.
  • It ensures that the semantic behaviour of the method stays consistent across different subclasses.

3. Final Classes

  • A final class cannot be subclassed. This is a way to declare a class as "final" or "complete" and it cannot be extended further.
  • It is useful when creating immutable classes like String or utility classes that should not be altered through inheritance.

What is finally in Java?

In Java, finally is a block used in conjunction with exception handling. It is part of the try-catch-finally construct and has the following characteristics:

1. Usage in Exception Handling

  • The finally block is always executed after the try and catch blocks, regardless of whether an exception was thrown or caught.
  • It is typically used for cleanup activities, such as closing file streams, releasing resources, or other necessary housekeeping tasks that should occur regardless of whether an error occurred or not.

2. Execution Characteristics

  • The code inside a finally block will execute even if there's a return statement in the try or catch blocks.
  • The only scenarios in which the finally block will not execute are if the JVM exits during the try or catch block, or if the thread executing the try or catch block is interrupted or killed.

3. Example

Here's a simple example to illustrate the use of finally


 
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handler
} finally {
// This block is executed regardless of an exception
// Typically used for cleanup activities
}
Copy code

4. Importance

  • The finally block is crucial for preventing resource leaks. For instance, if your try block opens a file for reading and an exception occurs, without a finally block to close the file, it would remain open.
  • It ensures that important cleanup tasks are performed even if an unexpected exception disrupts the normal flow of code execution.

What is finalize in Java?

In Java, finalize is a method that is part of the Object class, the superclass of all classes in Java. The finalize method is called by the garbage collector on an object when there are no more references to that object, just before the garbage collector reclaims the memory used by the object. It's primarily intended for an object to release system resources or to perform other cleanup operations before it is garbage collected. Here are key points about finalize in Java:

1. Method Definition

The finalize method is declared in the Object class as protected void finalize() throws Throwable.

2. Usage and Purpose

  • It's used to perform cleanup operations on objects that the garbage collector is about to collect.
  • Typically, these cleanup operations might include closing file streams, releasing network connections, or freeing up any other system resources that the object holds.

3. Automatic Invocation

  • You do not call the finalize method explicitly in your code. It is invoked automatically by the garbage collector.
  • There is no guarantee when, or even if, the finalize method will be invoked. The timing depends on the garbage collector, which operates asynchronously.

4. Override in Subclasses

Subclasses override the finalize method to dispose of system resources or to perform other cleanup.

5. Caution in Use

  • Relying on finalize is generally not recommended. It creates unpredictability since you can't be certain when, or even if, the garbage collector will invoke it.
  • The use of finalize is often associated with poor performance and unpredictable behaviour. As of Java 9 and later, the finalize method is deprecated.

6. Alternatives

Java offers better alternatives for managing resources, such as try-with-resources and the AutoCloseable interface, which provide a more predictable way of releasing resources.

7. Example

Here is a basic example of overriding the finalize method


 
class Example {
// Object creation and usage
protected void finalize() throws Throwable {
try {
// cleanup code, like closing resources
} finally {
super.finalize();
}
}
}
Copy code

Getting Started with Java Hello World Program

What are Identifiers in Java?

Understanding Variables in Java

Thus, each of these plays a vital role in Java programming, but they serve very different purposes and should be understood and used accordingly to write efficient and clean Java code.

Check out Java courses here!

FAQs

What is final in Java?

final is a keyword used to apply restrictions on classes, methods, and variables. A final class cannot be subclassed, a final method cannot be overridden by subclasses, and a final variable's value cannot be changed once it's initialized.

What is finally in Java?

finally is a block that follows a try block or a try-catch block. It is executed after the try block and any catch blocks, regardless of whether an exception was thrown or caught. It is typically used to close resources or to release locks, guaranteeing that these actions occur even if an error occurs within the try block.

What is finalize in Java?

finalize is a method that is called by the garbage collector on an object when it determines that there are no more references to the object. It's used to perform cleanup operations before the object is garbage collected, but it is not recommended to rely on it because it's unpredictable when it will be called, or if it will be called at all.

Can final and finally be used interchangeably?

No, they serve very different purposes. final is a modifier for classes, methods, and variables, whereas finally is a block that provides a mechanism to execute code whether an exception occurs or not. They cannot be substituted for one another.

Why is it advised to avoid using finalize in Java?

The use of finalize is generally discouraged because it creates unpredictability in the application. The garbage collector does not guarantee when it will call the finalize method, or even if it will call it at all, leading to potential resource leaks. Instead, it is better to use try-with-resources or explicit resource management strategies. Additionally, excessive use of finalizers can lead to performance issues.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio