</>

Technology

Core Java

Difficulty

Beginner

Interview Question

What is the difference between final, finally, and finalize in Java?

Answer

final vs finally vs finalize

These three sound similar but serve completely different purposes.

1. final — Keyword to Restrict

final variable — constant (cannot be reassigned)

Java
final int MAX_RETRY = 3;
MAX_RETRY = 5;  // ❌ compile error — cannot reassign final variable

final method — cannot be overridden

Java
class Parent {
    public final void display() {
        System.out.println("Cannot override this");
    }
}

class Child extends Parent {
    // @Override
    // public void display() { }  // ❌ compile error
}

final class — cannot be extended (subclassed)

Java
public final class String { ... }  // Java's String is final
// class MyString extends String { } // ❌ compile error

2. finally — Always Executes Block

Part of try-catch. The finally block always runs — whether an exception occurred or not. Used for cleanup (closing connections, drivers, files).

Java
WebDriver driver = null;
try {
    driver = new ChromeDriver();
    driver.get("https://example.com");
    // test logic...

} catch (Exception e) {
    System.out.println("Test failed: " + e.getMessage());

} finally {
    // Always runs — even if test throws exception
    if (driver != null) {
        driver.quit();  // always close the browser
    }
}

finally does NOT run only when:

  • System.exit() is called
  • JVM crashes

3. finalize — Called Before GC (Deprecated)

The finalize() method is called by the Garbage Collector before destroying an object. Deprecated since Java 9 — unreliable, don''t use it.

Java
public class Resource {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Object being GC'd — cleanup");
        super.finalize();
    }
}

Better alternative: Use try-with-resources or explicit cleanup.

Comparison Table

Featurefinalfinallyfinalize
TypeKeywordBlockMethod
Applied toVariables, Methods, Classestry-catch blockObject
PurposeRestrict modificationGuaranteed cleanupPre-GC cleanup
Mandatory?OptionalOptionalOptional (auto-called)
StatusActiveActiveDeprecated (Java 9+)

try-with-resources (Modern Alternative to finally)

Java
// Automatically closes resources — no finally needed
try (WebDriver driver = new ChromeDriver()) {
    driver.get("https://example.com");
    // driver.quit() called automatically when try block exits
}

Follow AutomateQA

Related Topics