These are syntactically different concepts even syntactically. Similar to discussing
Object methods, this question is a conversation starter.
finalize
– This is a finalizer method from the
Object
class, which is already discussed in the
previous post.
final
– A modifier that can be applied to variables, fields, methods, and classes. A variable or field declared final becomes immutable and has to be
initialized. A final method cannot be overridden in subclasses. A final class cannot have any subclasses at all. It is used to create a good (
Effective Java Item 15) API based on the principle of least privilege.
When a method uses a local variable from an outer scope, that variable has to be
effectively final. In this case, the
final
keyword is not mandatory, but the value still must not change.
finally
– This is part of the
try-catch-finally language construct.
Any exception thrown from the
try
block moves the execution to the most appropriate
catch
block, if present. This dictates the need to arrange
catch
blocks in strict order, from the type of the exception that is a descendant to its parent. In the case of a multicatch, the same order must be maintained within a single catch.
More examples about order.
After that the
finally
block is executed. It executes regardless of whether an exception occurred or not. It is typically used for resource release or other mandatory concluding actions.
For classes that require finalization ("resources"), the
AutoCloseable
interface is added. Repetitive code of the
final
block is moved to the
close
method and is implicitly called at the end of a
try-with-resources block. If an explicit
finally
is also present, it will be executed afterward.