[!INDEX]
- final Keyword (1 point)
- finalize() Method (7 points )
- finally Block (5 points )
- compare table
- Example Combining All Three code
1. final Keyword (1 point)
[!NOTE]
- The
finalkeyword is used to apply restrictions on variables, methods, and classes.
2. finalize() Method (7 points )
[!NOTE]
- The finalize() method is related to garbage collection in Java.
- called by the Garbage Collector when an object is about to be removed from memory.
- allows you to clean up resources (like closing a file or releasing system resources) before the object is destroyed.
- It's part of the Object class, so every class has it.
- Not guaranteed to be called immediately or even at all.
- Garbage collection in Java is non-deterministic.
- Deprecated since Java 9 because there are better ways to manage resources (like try-with-resources).
3. finally Block (5 points )
[!NOTE]
- used in exception handling and is always executed, whether an exception is handled or not.
- used to execute code such as closing resources like files or database connections.
- Used with try and catch.
- Ensures that crucial cleanup code runs after the
try block, even if an exception occurs.- It's optional, but when used, it always runs after the
tryandcatchblocks.
4. compare table
| Concept | Description | Purpose | Example |
|---|---|---|---|
final |
Keyword used to make variables, methods, or classes non-modifiable. | Prevents changes to variables, prevents method overriding, and prevents inheritance. | final int a = 10; |
finalize() |
Method called by the garbage collector before an object is destroyed. | Used for cleanup operations before object destruction. | protected void finalize() throws throwable{ } |
finally |
Block used in exception handling, always executed after try-catch. |
Ensures the execution of cleanup code like closing resources. | try-finally or try-catch-finally |
5. Example Combining All Three code
public class Example {
// Using 'final'
final int CONSTANT = 10;
public static void main(String[] args) {
try {
// Code that may throw an exception
int data = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught exception");
} finally {
// 'finally' block
System.out.println("Finally block executed");
}
Example example = new Example();
example = null;
// Requesting garbage collection
System.gc();
}
// 'finalize' method
@Override
protected void finalize() {
System.out.println("Finalize method called before object is destroyed");
}
}