Difference Between final
, finally
, and finalize()
in Java
In Java, the terms final, finally, and finalize() often confuse beginners due to their similar names. However, each has a very different purpose and use case. Let’s break them down in detail.
1. final
Keyword
1.1 final Variable
final int MAX_AGE = 100;
// MAX_AGE = 90; // Compilation error
1.2 final Method
class Animal {
final void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
// void sound() {} // Error
}
1.3 final Class
final class Constants {
public static final double PI = 3.14159;
}
// class ExtendedConstants extends Constants {} // Error
2. finally
Block
public class TryFinallyExample {
public static void main(String[] args) {
try {
int data = 100 / 5;
System.out.println(data);
} catch (Exception e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("finally block executed");
}
}
}
Output
20
finally block executed
3. finalize()
Method
protected void finalize() throws Throwable {
// cleanup code
super.finalize();
}
Example
public class FinalizeExample {
protected void finalize() {
System.out.println("Finalize method called");
}
public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
obj = null;
System.gc(); // Suggests GC
}
}
Summary Table
Feature | final | finally | finalize() |
---|---|---|---|
Type | Keyword | Block | Method |
Usage | Restrict modification | Exception handling cleanup | Garbage collection cleanup |
Called by | Programmer | JVM during try-catch | JVM during GC |
Modern Use | Recommended | Recommended | Deprecated |
Conclusion
Understanding the difference between final
, finally
, and finalize()
helps you write more secure and efficient Java code. Use them wisely according to their purpose.
๐ Related Posts
๐ก Exception Handling in Java
Understand how try-catch-finally works and how to use it effectively in Java applications.
๐ง Java Memory Leaks
Learn how final objects and finalize() relate to memory management and GC behavior.
๐งช Coding Round Questions
Practice interview-style problems involving final variables and memory concepts.
๐ฏ Top 25 Java Interview Qs
Brush up on frequently asked questions including final vs finally vs finalize.