These three terms look similar but serve completely different purposes in Java. This is a very common interview question.
🔹 1. final Keyword
final is a keyword used to restrict modification.
Uses of final
- Final Variable → Value cannot be changed (constant)
- Final Method → Cannot be overridden
- Final Class → Cannot be inherited
Example
final int x = 10;
// x = 20; ❌ Error (cannot change value)
🔹 2. finally Block
finally is a block used in exception handling.
It always executes whether an exception occurs or not.
Purpose
- Close resources
- Database connections cleanup
- File handling cleanup
Example
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Exception handled");
} finally {
System.out.println("Finally block executed");
}
🔹 3. finalize() Method
finalize() is a method called by the Garbage Collector before destroying an object.
Purpose
- Perform cleanup before object removal
- Release system resources
Example
class Test {
protected void finalize() {
System.out.println("Object destroyed");
}
}
⚠️ Note: finalize() is deprecated in modern Java versions and should generally be avoided.
🔹 Key Differences
| Feature | final |
finally |
finalize() |
|---|---|---|---|
| Type | Keyword | Block | Method |
| Used In | Variables, Methods, Classes | Exception Handling | Garbage Collection |
| Purpose | Restrict modification | Always execute cleanup code | Cleanup before object removal |
| Execution Time | Compile time rule | After try/catch | Before GC removes object |
✅ Easy Interview Line
- final → restriction
- finally → always executes
- finalize() → called by Garbage Collector
✅ Promotional Content
To learn Java core concepts like exception handling, memory management, JVM internals, and real-time coding practices through practical projects, join the Top Java Real Time Projects Online Training in Ameerpet.
Top comments (0)