Sobes.tech
Middle

What are the keywords final and finalize in Java, and what is the difference between them?

sobes.tech AI

Answer from AI

final - a keyword to denote immutability:

  • Variable: The reference or value cannot be changed after initialization.
  • Method: The method cannot be overridden in a subclass.
  • Class: The class cannot be inherited.

finalize() - a method called by the garbage collector before an object is removed from memory. It is located in the Object class and is intended for releasing external resources.

Differences:

final finalize()
Keyword Method
Indicates immutability Called before object deletion
Related to declaration Related to the object's lifecycle
Applied to variables, methods, classes Applied only to objects

Example of using final:

public class FinalExample {
    final int finalVariable = 10;

    final void finalMethod() {
        // immutable method logic
    }
}

final class FinalClass {
    // content
}

Example of using finalize():

public class FinalizeExample {
    @Override
    protected void finalize() throws Throwable {
        try {
            // Clean up external resources, like closing a connection
            System.out.println("Finalizing FinalizeExample object...");
        } finally {
            super.finalize(); // Always call super.finalize()
        }
    }
}

Important: Using finalize() is not recommended in modern Java due to unpredictable timing and potential performance issues. It is preferable to use try-with-resources blocks for resource management.

What are the keywords final and finalize in Java, and… - sobes.tech