[!INDEX]

  1. final Keyword (1 point)
  2. finalize() Method (7 points )
  3. finally Block (5 points )
  4. compare table
  5. Example Combining All Three code

1. final Keyword (1 point)

[!NOTE]

  1. The final keyword is used to apply restrictions on variables, methods, and classes.

2. finalize() Method (7 points )

[!NOTE]

  1. The finalize() method is related to garbage collection in Java.
  2. called by the Garbage Collector when an object is about to be removed from memory.
  3. allows you to clean up resources (like closing a file or releasing system resources) before the object is destroyed.
  4. It's part of the Object class, so every class has it.
  5. Not guaranteed to be called immediately or even at all.
  6. Garbage collection in Java is non-deterministic.
  7. Deprecated since Java 9 because there are better ways to manage resources (like try-with-resources).

3. finally Block (5 points )

[!NOTE]

  1. used in exception handling and is always executed, whether an exception is handled or not.
  2. used to execute code such as closing resources like files or database connections.
  3. Used with try and catch.
  4. Ensures that crucial cleanup code runs after the try block, even if an exception occurs.
  5. It's optional, but when used, it always runs after the try and catch blocks.

4. compare table

Concept Description Purpose Example
final Keyword used to make variables, methods, or classes non-modifiable. Prevents changes to variables, prevents method overriding, and prevents inheritance. final int a = 10;
finalize() Method called by the garbage collector before an object is destroyed. Used for cleanup operations before object destruction. protected void finalize() throws throwable{ }
finally Block used in exception handling, always executed after try-catch. Ensures the execution of cleanup code like closing resources. try-finally
or
try-catch-finally

5. Example Combining All Three code

public class Example {
    // Using 'final'
    final int CONSTANT = 10;
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            int data = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Caught exception");
        } finally {
            // 'finally' block
            System.out.println("Finally block executed");
        }
        Example example = new Example();
        example = null;
        // Requesting garbage collection
        System.gc();
    }

    // 'finalize' method
    @Override
    protected void finalize() {
        System.out.println("Finalize method called before object is destroyed");
    }
}