Questions
What is the difference between `final`, `finally`, and `finalize` in Java?
The Scenario
You are a backend engineer at a fintech company. You are writing a new service that needs to work with a variety of different data types.
The Challenge
Explain the difference between the final, finally, and finalize keywords in Java.
A junior engineer might confuse these three keywords. They might not be aware of the difference in their purpose or how they are used.
A senior engineer would be able to provide a detailed explanation of the differences between `final`, `finally`, and `finalize`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Key Differences
| Keyword | Description |
|---|---|
final | A keyword that can be used to make a variable, method, or class immutable. |
finally | A block of code that is always executed, regardless of whether an exception is thrown. |
finalize | A method that is called by the garbage collector just before an object is garbage collected. |
Step 2: Code Examples
Here are some code examples that show the difference between the three keywords:
final:
public class MyClass {
public final int MY_CONSTANT = 10;
public final void myMethod() {
// ...
}
}finally:
try {
// ...
} catch (Exception e) {
// ...
} finally {
// This block is always executed.
}finalize:
public class MyClass {
@Override
protected void finalize() throws Throwable {
// This method is called by the garbage collector.
}
}When to use each
- Use
finalto create constants and to prevent a method or class from being overridden. - Use
finallyto release resources, such as file handles and database connections. - Avoid using
finalize. It is not guaranteed to be called, and it can make your code more difficult to reason about.
Practice Question
You are writing a function that opens a file. Which of the following would be the most appropriate way to close the file?