Difference between final, finally, and finalize in Java

In Java, the terms final, finally, and finalize() may look and sound similar, but they serve completely different purposes. While beginners often confuse them, each has its unique use case — one deals with immutability, another with exception handling, and the last one with garbage collection.

In this article, we will dive deep into each of these keywords/methods, understand what they do, how they work, and explore real examples to avoid confusion.

1. What is final in Java?

final is a keyword in Java that is used to restrict the behavior of variables, methods, and classes. Once something is marked as final, it cannot be changed or modified.

✅ Use Cases of final:

a. Final Variables:

A variable declared as final cannot be reassigned once initialized.

final int x = 100;
x = 200; // ❌ Compile-time error

This is useful when you want to create constants.

b. Final Methods:

A method marked as final cannot be overridden by subclasses.

class Parent {
final void show() {
System.out.println("Parent method");
}
}

class Child extends Parent {
// void show() { } ❌ Compile-time error: Cannot override final method
}

c. Final Classes:

A class declared as final cannot be extended (i.e., inherited).

final class Vehicle {
void start() {
System.out.println("Vehicle starting...");
}
}

// class Car extends Vehicle { } ❌ Error: Cannot inherit from final class

Summary of final:

2. What is finally in Java?

finally is a block in Java used in exception handling. It always executes after the try-catch block, regardless of whether an exception was thrown or caught.

It is typically used to release resources like files, database connections, or network sockets.

Syntax of finally:

try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling
} finally {
// Code that always executes
}

Example:

public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("This block always executes");
}
}
}

Output:

Exception caught: java.lang.ArithmeticException: / by zero
This block always executes

Key Facts:

  • Even if no exception is thrown, the finally block runs.
  • Even if return is used in the try or catch, finally still runs.

Typical Use of finally:

try {
// Open a file
} catch (IOException e) {
// Handle error
} finally {
// Close the file
}

3. What is finalize() in Java?

finalize() is a method in Java that is used for cleanup operations before an object is garbage collected. It is defined in the java.lang.Object class and can be overridden by subclasses.

Note: finalize() is now considered deprecated starting from Java 9 and removed in Java 18, so it’s rarely used in modern applications.

✅ Purpose of finalize():

It was typically used to release system resources or perform other cleanup before the object is removed from memory.

🔧 Syntax:

protected void finalize() throws Throwable {
// cleanup code
}

Example:

public class FinalizeExample {
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize method called");
}

public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
obj = null; // Eligible for GC
System.gc(); // Request JVM to run GC
}
}

Output (Not Guaranteed):

Finalize method called

Key Points:

  • JVM may or may not call finalize() immediately.
  • It is called once per object before it is garbage collected.
  • Cannot be used as a reliable resource cleanup mechanism.
  • Better alternative: Use try-with-resources and implement AutoCloseable.

Comparison Table: final vs finally vs finalize()


Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare