Interview #225: Java - Difference between final, finally and finalize?
final, finally, and finalize in Java — all of which may sound similar but serve very different purposes in the Java programming language.
Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-6232667387
✅ 1. final (Keyword)
Purpose: To declare constants, prevent inheritance or method overriding.
The final keyword is used in several contexts in Java, and it has different meanings depending on where it is applied:
🔹 a. Final Variable:
A final variable can only be initialized once and its value cannot be changed after that.
final int MAX_VALUE = 100;
MAX_VALUE = 200; // Compile-time error
🔹 b. Final Method:
A final method cannot be overridden by subclasses.
class A {
final void show() {
System.out.println("This is a final method.");
}
}
class B extends A {
void show() { // Compile-time error
System.out.println("Trying to override.");
}
}
🔹 c. Final Class:
A final class cannot be subclassed/inherited.
final class Vehicle {
// class code
}
class Car extends Vehicle { // Compile-time error
}
💡 Common Use Case: Making classes like String final to ensure immutability and prevent unwanted modification via inheritance.
✅ 2. finally (Block)
Purpose: To define a block of code that is always executed after a try-catch block — whether or not an exception is thrown or caught.
Recommended by LinkedIn
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("This will always be executed.");
}
🔹 Key Points:
try {
// risky code
} finally {
// cleanup code
}
💡 Best Practice: Always use finally for cleanup code that must execute regardless of exceptions.
✅ 3. finalize() (Method)
Purpose: Acts as a clean-up mechanism before an object is garbage collected.
🔹 Signature:
protected void finalize() throws Throwable {
// cleanup code
}
class MyClass {
protected void finalize() throws Throwable {
System.out.println("Object is being garbage collected");
}
}
⚠️ Note: As of Java 9, finalize() is deprecated because it causes performance issues and is unreliable. Developers are encouraged to use try-with-resources or explicit resource management instead.
🧠 Summary Table