> For the complete documentation index, see [llms.txt](https://qatesting.gitbook.io/qa/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://qatesting.gitbook.io/qa/java/oops/constructor/finalization.md).

# Finalization

## 🚨 The Final Frontier of Java Keywords 🚨

The dynamic trio of `final`, `finally`, and `finalize()` serve unique purposes though they sound similar! Let's break it down:

### The Immutable `final` 🔒

📌 Rules of `final`:

```java
final int MAX_VALUE = 100; // Constant 

final public void print() { // Method 
   //...
}

final class Car { // Class
   //... 
}
```

* Declares immutable properties ❌🔀
* Prevent overriding in subclasses 🚫
* Commonly used for constants 📏

#### Key Benefits:

* Avoid unintended changes 🙅‍♂️
* Enforce architectural rules 👮
* Improved understandability 💡

### The Unstoppable `finally` 🚥

🧐 Purpose of `finally`:

```java
try {
  // Exception prone code
}
catch (Exception e) {
  // Handle exception
}
finally {
  // Always executes after try/catch ✅
} 
```

* Guaranteed execution before method exit 🏁
* Commonly closes resources 🗑️

#### Why use `finally`?

* Release external resources 🖇️
* Restore program state 💾
* Critical code that must run ✅

### The Destructor `finalize()` 👋

🔚 When `finalize()` gets called:

```java
protected void finalize() { 
//Cleanup before garbage collection
  super.finalize(); 
}
```

* Just before object is garbage collected 🗑️
* Rarely used nowadays
* `try-finally` preferred

#### Downsides of`finalize()`:

* Not guaranteed to run 🤷‍♂️
* Causes performance issues 🔥
* Anti-pattern in most cases ❌

So while they sound similar, each handles unique responsibilities!
