Junior — Middle
Explain the differences between the keywords 'final', the 'finally' block, and the 'finalize' method in Java.
sobes.tech AI
Answer from AI
In Java, the keywords and constructs final, finally, and the method finalize() have different purposes:
-
final — a modifier that can be applied to variables, methods, and classes.
- For variables,
finalmeans the value cannot be changed after initialization. - For methods,
finalmeans the method cannot be overridden in subclasses. - For classes,
finalmeans the class cannot be inherited.
- For variables,
-
finally — a block used with try-catch to ensure code execution regardless of whether an exception occurred. Usually, resource release code is placed here.
try {
// code
} catch(Exception e) {
// handling
} finally {
// this code always executes
}
- finalize() — a method of the Object class called by the garbage collector before an object is removed from memory. Its use is discouraged because its invocation is not guaranteed and it can cause performance issues.
In summary, final is for restricting modifications, finally for guaranteed execution, and finalize() for cleanup before garbage collection (deprecated mechanism).