Junior
What are the final and finalize keywords in Java, and how do they differ?
sobes.tech AI
Answer from AI
In Java, final and finalize are different concepts with different purposes:
finalis a keyword used to declare:- Constants (variables that cannot be changed after initialization).
- Methods that cannot be overridden in subclasses.
- Classes that cannot be inherited.
Example:
final int x = 10; // x cannot be changed
final class MyClass {} // class cannot be inherited
final void myMethod() {} // method cannot be overridden
finalize()is a method of theObjectclass, called by the garbage collector before an object is removed from memory. It is intended for resource cleanup, but its use is not recommended because its invocation is not guaranteed and may lead to unpredictable behavior.
Example:
@Override
protected void finalize() throws Throwable {
// resource cleanup
super.finalize();
}
Differences:
finalis a keyword for controlling code modification.finalizeis a method for cleanup before garbage collection, but it is deprecated and not recommended for use.