final vs finally vs finalize
TL;DR
These three keywords sound identical but have absolutely nothing to do with each other:
final: A modifier that prevents mutation (variables cannot be reassigned, methods cannot be overridden, classes cannot be extended).finally: A block in atry-catchstatement that is guaranteed to execute, regardless of whether an exception occurred.finalize(): A deprecated method called by the Garbage Collector before destroying an object. (Never use it).
Concept
final is about design intent. If you declare final double PI = 3.14, the compiler will throw an error if anyone tries to change it. If you declare public final class String, no one can extend it and mess with its internal logic.
finally is about resource management. If you open a database connection in a try block, and the code crashes, the connection remains open, causing a leak. Putting connection.close() in the finally block guarantees the connection is closed, crash or no crash.
finalize() was an old Java 1.0 feature meant to let objects clean themselves up right before they were deleted from RAM. It was highly unpredictable, caused severe performance issues, and has been officially deprecated since Java 9.
Examples
// 1. FINAL CLASS
// No class can 'extend' this DatabaseConnector.
public final class DatabaseConnector {
// FINAL VARIABLE
// Cannot be reassigned after initialization.
private final String url = "jdbc:mysql://localhost:3306/db";
// FINAL METHOD
// Even if the class wasn't final, no child class could override this method.
public final void connect() {
// ...
}
}
// 2. FINALLY BLOCK
public void readFile() {
File file = new File("data.txt");
try {
// Read file (might crash)
} catch (Exception e) {
System.out.println("Crashed!");
} finally {
// GUARANTEED to execute, even if the catch block throws another exception!
System.out.println("Closing resources...");
}
}
// 3. FINALIZE (Deprecated - DO NOT USE)
class LegacyObject {
@Override
protected void finalize() throws Throwable {
System.out.println("Garbage collector is destroying me!");
}
}
Interview Questions
Q: Does a finally block ALWAYS execute?
A: In 99.9% of cases, yes. However, there are two edge cases where a finally block will not execute:
- If you explicitly call
System.exit(0)inside the try or catch block (which instantly kills the JVM). - If the JVM crashes entirely (e.g., memory hardware failure, or an
OutOfMemoryErrorso severe the JVM terminates abruptly).
Q: Since finalize() is deprecated, how should we clean up resources?
A: You should implement the AutoCloseable interface. Instead of waiting for the unpredictable Garbage Collector, AutoCloseable allows you to use the modern Try-With-Resources syntax. As soon as the try block finishes (or crashes), Java automatically and instantly calls the close() method, ensuring perfect, predictable resource management.