What is the Difference Between final, finally, and finalize in Java?
These three keywords look similar but serve completely different purposes in Java.
1. final (Keyword/Modifier)
Used to create constants, prevent method overriding, and prevent inheritance.
public class FinalExample {
// final variable - constant
public final double PI = 3.14159;
private final int MAX_VALUE;
// Blank final variable - must initialize in constructor
public FinalExample(int max) {
this.MAX_VALUE = max;
}
// final method - cannot be overridden
public final void display() {
System.out.println("Cannot override me");
}
// final class - cannot be extended
final class ImmutableClass {
private final int value;
ImmutableClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
// final parameter - cannot be modified
public void process(final int number) {
// number = 10; // ERROR: Cannot reassign final parameter
System.out.println("Number: " + number);
}
public static void main(String[] args) {
final int MAX = 100;
// MAX = 200; // ERROR: Cannot reassign final variable
FinalExample example = new FinalExample(1000);
System.out.println("PI: " + example.PI);
System.out.println("MAX_VALUE: " + example.MAX_VALUE);
// final reference - cannot reassign, but object can mutate
final StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // OK - object content changed
// sb = new StringBuilder("New"); // ERROR: Cannot reassign final reference
}
}
2. finally (Block)
Always executes after try-catch block, used for cleanup code.
public class FinallyExample {
// Example 1: Normal execution
public static void normalExecution() {
try {
System.out.println("Inside try - normal execution");
} catch (Exception e) {
System.out.println("Inside catch - won't execute");
} finally {
System.out.println("Finally - always executes");
}
}
// Example 2: Exception occurs
public static void exceptionOccurs() {
try {
System.out.println("
Inside try - about to throw exception");
int result = 10 / 0;
System.out.println("This won't print");
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally - always executes even with exception");
}
}
// Example 3: Exception not caught
public static void exceptionNotCaught() {
try {
System.out.println("
Inside try - throwing unchecked exception");
throw new RuntimeException("Unchecked exception");
} finally {
System.out.println("Finally - executes before exception propagates");
}
// Exception propagates after finally
}
// Example 4: With return statement
public static int testFinallyWithReturn() {
try {
System.out.println("
Inside try - about to return 1");
return 1;
} finally {
System.out.println("Finally - executes BEFORE return");
// return 2; // Would override return 1
}
}
// Example 5: Resource cleanup (traditional way)
public static void resourceCleanup() {
java.io.FileReader fr = null;
try {
fr = new java.io.FileReader("test.txt");
System.out.println("
File opened");
} catch (java.io.FileNotFoundException e) {
System.out.println("File not found: " + e);
} finally {
try {
if (fr != null) {
fr.close();
System.out.println("File closed in finally");
}
} catch (java.io.IOException e) {
System.out.println("Error closing file: " + e);
}
}
}
public static void main(String[] args) {
normalExecution();
exceptionOccurs();
try {
exceptionNotCaught();
} catch (RuntimeException e) {
System.out.println("Exception caught in main: " + e.getMessage());
}
int result = testFinallyWithReturn();
System.out.println("Return value: " + result);
resourceCleanup();
}
}
3. finalize (Method - Deprecated)
Called before garbage collection (deprecated since Java 9).
public class FinalizeExample {
private static int objectCount = 0;
private int id;
private String name;
public FinalizeExample(String name) {
this.id = ++objectCount;
this.name = name;
System.out.println("Object created: " + this);
}
@Deprecated
@Override
protected void finalize() throws Throwable {
try {
System.out.println("finalize() called for: " + this);
// Cleanup logic here
} finally {
super.finalize();
}
}
@Override
public String toString() {
return "Object[id=" + id + ", name=" + name + "]";
}
public static void main(String[] args) {
System.out.println("=== finalize() Demo ===");
System.out.println("Note: finalize() is deprecated since Java 9
");
// Create objects
for (int i = 1; i <= 5; i++) {
new FinalizeExample("Object-" + i);
}
System.out.println("
Created 5 objects");
System.out.println("Requesting garbage collection...");
// Request GC (finalize may or may not run)
System.gc();
// Wait for potential finalization
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("
=== Better Alternatives to finalize() ===");
System.out.println("1. try-with-resources for AutoCloseable");
System.out.println("2. Cleaner API (Java 9+)");
System.out.println("3. PhantomReference with ReferenceQueue");
}
}
// Better alternative: Cleaner API (Java 9+)
import java.lang.ref.Cleaner;
class Resource implements AutoCloseable {
private static final Cleaner cleaner = Cleaner.create();
private final Cleaner.Cleanable cleanable;
private final String name;
static class State implements Runnable {
private final String name;
State(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Cleaning up resource: " + name);
}
}
Resource(String name) {
this.name = name;
this.cleanable = cleaner.register(this, new State(name));
System.out.println("Resource created: " + name);
}
@Override
public void close() {
cleanable.clean();
System.out.println("Resource closed: " + name);
}
}
Complete Comparison Table
| Feature | final | finally | finalize |
|---|---|---|---|
| Type | Keyword/Modifier | Block | Method |
| Purpose | Restrict modification | Ensure code execution | Cleanup before GC |
| Used with | Variables, methods, classes | try-catch | Object class method |
| When executed | Compile-time | Always after try/catch | Before garbage collection |
| Status | Active | Active | Deprecated (Java 9) |
Practical Examples - All Three Together
public class CompleteComparison {
// final variable
private static final String APP_NAME = "Online Learner";
// Demonstrating all three
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
return -1;
} finally {
System.out.println("Division operation completed");
}
}
// final parameter and finally
public static void processResource(final String resourceName) {
java.io.BufferedReader reader = null;
try {
reader = new java.io.BufferedReader(
new java.io.FileReader(resourceName + ".txt"));
System.out.println("Reading from: " + resourceName);
} catch (java.io.FileNotFoundException e) {
System.out.println("Resource not found: " + resourceName);
} finally {
try {
if (reader != null) {
reader.close();
System.out.println("Resource closed: " + resourceName);
}
} catch (java.io.IOException e) {
System.out.println("Error closing: " + e);
}
}
}
public static void main(String[] args) {
System.out.println("Application: " + APP_NAME);
System.out.println("
=== Division Demo ===");
System.out.println("10/2 = " + divide(10, 2));
System.out.println("10/0 = " + divide(10, 0));
System.out.println("
=== Resource Processing ===");
processResource("config");
System.out.println("
=== Best Practices Summary ===");
System.out.println("final: Use for constants and immutability");
System.out.println("finally: Use for resource cleanup (traditional)");
System.out.println("finalize: AVOID - deprecated, use try-with-resources or Cleaner");
// Modern alternative to finally + finalize
System.out.println("
=== Modern Alternative: try-with-resources ===");
try (java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.StringReader("Hello World"))) {
System.out.println("Read: " + br.readLine());
} catch (java.io.IOException e) {
e.printStackTrace();
}
// Automatically closed - no need for finally
}
}
Master Java keywords with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
