DEV Community

Code Green
Code Green

Posted on

Explain difference between finally, final, and finalize in Java

Understanding finally, final, and finalize in Java

1. The final Keyword

The final keyword in Java is used to declare constants, prevent method overriding, and prevent inheritance. Here's how it works:

  • Final Variable: A variable declared as final cannot be changed once initialized.
  • Final Method: A method declared as final cannot be overridden by subclasses.
  • Final Class: A class declared as final cannot be extended.

Example of final

        final int MAX_VALUE = 100; // constant value
        final void display() { ... } // cannot be overridden
        final class Constants { ... } // cannot be subclassed
Enter fullscreen mode Exit fullscreen mode

2. The finally Block

The finally block is used in exception handling. It follows a try block and executes regardless of whether an exception is thrown or caught. This block is typically used for cleanup operations like closing database connections or file streams.

Example of finally

try {
        // code that may throw an exception
    } catch (Exception e) {
        // handle the exception
    } finally {
        // cleanup code that runs always
        System.out.println("This will always execute.");
    }
Enter fullscreen mode Exit fullscreen mode

3. The finalize Method

The finalize method is a protected method of the Object class that is called by the garbage collector before an object is removed from memory. It's used for releasing resources or performing cleanup operations before the object is reclaimed.

Example of finalize

        protected void finalize() throws Throwable {
            try {
                // cleanup code here
            } finally {
                super.finalize();
            }
        }
Enter fullscreen mode Exit fullscreen mode

Conclusion

In summary, final is a keyword for declaring constants and restricting inheritance, finally is used for executing a block of code after a try block, and finalize is a method for cleanup before an object is garbage collected. Understanding these concepts is essential for effective Java programming.

Top comments (0)