Java
Java Exception Handling
Final, Finally, Finallize

Difference Between final, finally, and finalize

Featurefinalfinallyfinalize
DefinitionAn access modifier used to restrict class, method, or variableA block that executes important code whether an exception occurs or notA method used to clean up resources before garbage collection
Applicable ToClasses, methods, and variablesTry-catch blockObjects
FunctionalityPrevents modification, inheritance, or overridingEnsures execution of important codePerforms cleanup before object destruction
ExecutionExecuted when calledAlways executed after try-catchExecuted before garbage collection

Example of final:

public class FinalExample {
    final int age = 18;
    void display() {
        age = 55; // Compile-time error
    }
}

Example of finally:

try {
    int data = 25 / 0;
} catch (ArithmeticException e) {
    System.out.println("Exception handled");
} finally {
    System.out.println("finally block always executes");
}

Example of finalize:

protected void finalize() {
    System.out.println("Called finalize method");
}