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)
final int MAX_RETRY = 3;
MAX_RETRY = 5; // ❌ compile error — cannot reassign final variable
final method — cannot be overridden
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)
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).
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.
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
| Feature | final | finally | finalize |
|---|---|---|---|
| Type | Keyword | Block | Method |
| Applied to | Variables, Methods, Classes | try-catch block | Object |
| Purpose | Restrict modification | Guaranteed cleanup | Pre-GC cleanup |
| Mandatory? | Optional | Optional | Optional (auto-called) |
| Status | Active | Active | Deprecated (Java 9+) |
try-with-resources (Modern Alternative to finally)
// Automatically closes resources — no finally needed
try (WebDriver driver = new ChromeDriver()) {
driver.get("https://example.com");
// driver.quit() called automatically when try block exits
}
