- final” is the keyword to declare a constant AND prevents a class from producing subclasses.
- “finally” is a block of code that always executes when the try block is finished, unless System.exit() was called.
- “finalize()” is an method that is invoked before an object is discarded by the garbage collector.
In Core Java, final
, finally
, and finalize
are related concepts, but they serve different purposes.
final
keyword:final
is a keyword used in Java to declare a constant, apply restrictions on a class, method, or variable.- When used with a variable, it means the variable’s value cannot be changed once it has been assigned.
- When used with a method, it means the method cannot be overridden in any subclass.
- When used with a class, it means the class cannot be subclassed.
Example:
javafinal int x = 10;
final class MyClass { /* ... */ }
finally
block:finally
is a block that follows atry
block in a try-catch-finally statement.- The code inside the
finally
block is guaranteed to be executed, whether an exception is thrown or not. - It is often used for cleanup operations, such as closing resources (e.g., closing a file or a database connection).
Example:
javatry {
// Code that may throw an exception
} catch (Exception e) {
// Handle the exception
} finally {
// Code that always gets executed, regardless of whether an exception occurred
}
finalize
method:finalize
is a method in theObject
class in Java.- It is called by the garbage collector before an object is reclaimed (destroyed) by the garbage collector.
- It allows an object to perform cleanup operations before it is garbage collected. However, its usage is discouraged in modern Java programming due to more effective alternatives, such as the
AutoCloseable
interface and try-with-resources.
Example (not recommended, for illustration purposes):
javaclass MyClass {
// other methods and fields@Override
protected void finalize() throws Throwable {
// Cleanup code before the object is garbage collected
// ...
super.finalize();
}
}
In summary:
final
is a keyword used for declaring constants, restricting class inheritance, and preventing method overriding or variable reassignment.finally
is a block used in exception handling to ensure a piece of code is always executed, regardless of whether an exception occurs or not.finalize
is a method in theObject
class used for cleanup operations before an object is garbage collected, but it is generally discouraged in modern Java programming.