What is the difference between final, finally, and finalize in Java?

Interview question: What is the difference between final, finally, and finalize in Java?

The answer:

Basic Answer

1. Final is a keyword.

2. Finally is a code block.

3. Finalize is a method.

Further Explanation

The final keyword is used to apply restrictions to classes, methods, and variables. Applied to a class, it prevents the class from being extended. Applied to a method, it prevents the method from being overridden in a derived class. Applied to a variable, it prevents the variable from being reassigned, although the data stored within the variable may still be mutable, depending on whether the object is immutable or not.

The finally code block is for code that should execute whether or not an exception is thrown from a try block. Common usage of the finally block is for closing resources such as database connections or reading from files. Although, in Java 1.7+, there is a simpler, more elegant syntax of ensuring resources are closed by using the try-with-resources block.

Finalize is a method that is called, directly prior to garbage collection, commonly used to clean up processing before the object is reclaimed.