What are final, finally and finalize in Java? Can you distinguish and compare them?
In Java, final
, finally
, and finalize
are three distinct concepts that serve different purposes. Here’s a breakdown of each:
final
final
, its value cannot be changed once it has been assigned. This means that it acts as a constant.
final int x = 10;
// x = 20; // This will cause a compilation error
final
cannot be overridden by subclasses.
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// void display() { } // This will cause a compilation error
}
final
cannot be subclassed.
final class FinalClass {
// class body
}
// class SubClass extends FinalClass { } // This will cause a compilation error
finally
finally
block is used to execute a block of code after a try
block, regardless of whether an exception was thrown or caught. It is typically used for cleanup activities, such as closing resources (like files or database connections).
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle exception
} finally {
// This block will always execute
System.out.println("This will always execute.");
}
finalize
Object
class.finalize()
method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It is used to perform cleanup before the object is reclaimed by the garbage collector.
protected void finalize() throws Throwable {
try {
// Cleanup code, like releasing resources
} finally {
super.finalize();
}
}
finalize()
is generally discouraged in modern Java programming due to unpredictability in when it will be called and performance issues. Instead, it is recommended to use try-with-resources or explicit resource management.final
: A keyword for defining constants, preventing method overriding, and preventing class inheritance.finally
: A block used in exception handling that executes after a try
block, regardless of whether an exception occurred.finalize
: A method for cleanup before an object is garbage collected, but its use is discouraged in favor of better resource management practices.These three concepts are fundamental in Java, and understanding their differences is crucial for effective programming in the language.